pythoncctypes

How to pass Bytes buffer from Python to C


I'm experimenting with native C extensions in Python. What I'm trying to accomplish now is to pass Bytes buffer from Python to C.

I need to load a binary file from disk and pass that buffer to C extension however I have no clue what types should I use. What I have now is:

Python part:

import ctypes

lib = ctypes.cdll.LoadLibrary("lib.so")

f = open("file.png", "rb")
buf = f.read()
f.close()

lib.func(buf)

C part:

#include <stdio.h>

void func(int buf) {
    // do something with buf
}

Solution

  • Example solution passing binary data and length to C function which dumps it.

    Python part:

    import ctypes
    
    lib = ctypes.cdll.LoadLibrary("./lib.so")
    f = open("file.png", "rb")
    buf = f.read()
    f.close()
    
    lib.func.argtypes = [ctypes.c_void_p, ctypes.c_uint]
    lib.func(ctypes.cast(buf, ctypes.c_void_p), len(buf))
    

    C part:

    #include <stdio.h>
    
    void func(unsigned char *buf, unsigned int len) {
        if (buf) {
            for (unsigned int i=0; i<len; i++) {
                if (i%16 == 0) {
                    printf("\n");
                }
                printf("0x%02x ", buf[i]);
            }
            printf("\n");
        }
    }