代码之家  ›  专栏  ›  技术社区  ›  Pono

如何将Bytes缓冲区从Python传递到C

  •  -1
  • Pono  · 技术社区  · 4 年前

    我正在Python中尝试原生C扩展。我现在要做的是将Bytes缓冲区从Python传递给C。

    我需要从磁盘加载一个二进制文件,并将该缓冲区传递给C扩展名,但我不知道应该使用什么类型。我现在拥有的是:

    Python部分:

    import ctypes
    
    lib = ctypes.cdll.LoadLibrary("lib.so")
    
    f = open("file.png", "rb")
    buf = f.read()
    f.close()
    
    lib.func(buf)
    

    C部分:

    #include <stdio.h>
    
    void func(int buf) {
        // do something with buf
    }
    
    0 回复  |  直到 4 年前
        1
  •  1
  •   Mathias Schmid    4 年前

    示例解决方案将二进制数据和长度传递给C函数,C函数将其转储。

    Python部分:

    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部分:

    #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");
        }
    }