【问题标题】:Python ctypes: how to allocate output buffer for C function in callbackPython ctypes:如何在回调中为 C 函数分配输出缓冲区
【发布时间】:2019-05-11 02:46:42
【问题描述】:

我在 c 代码中将下一个回调作为函数中的参数之一:

typedef unsigned char* (*my_callback)(int size);
//for example:
unsigned char * tmp_buff = nullptr;
tmp_buff = i_alloc_fn(10);
printf("Tmp buff addr = %d.\n", tmp_buff);
*tmp_buff = 111;
printf("I am still alive");

我正在尝试从 python 提供此回调(C 代码作为 .so lib 加载)。我尝试了两种方法。

ALLOC_CALLBACK_FUNC = ctypes.CFUNCTYPE(ctypes.c_char_p, ctypes.c_int)
#...
def py_alloc_callback(size):
    libc = ctypes.CDLL("libc.so.6") 
    mem_ptr = libc.malloc(ctypes.c_uint(size))
    return mem_ptr

还有

ALLOC_CALLBACK_FUNC = ctypes.CFUNCTYPE(ctypes.c_char_p, ctypes.c_int)
stringbuffer = ''
#...
def py_alloc_callback(size):
    global stringbuffer
    stringbuffer=ctypes.create_string_buffer(size)

    return ctypes.POINTER(ctypes.c_ubyte)(stringbuffer)

但是当 C 代码尝试写入分配的内存时,这两种变体都会导致分段错误。 请帮我解决它

【问题讨论】:

    标签: python c python-2.7 memory ctypes


    【解决方案1】:

    现在可以了:

    def py_alloc_callback(size):
        libc = ctypes.CDLL("libc.so.6") 
        alloc_f = libc.malloc
        alloc_f.restype = ctypes.c_void_p
        alloc_f.argtypes = [ ctypes.c_uint ] 
        return alloc_f(ctypes.c_uint(size))
    

    【讨论】:

      【解决方案2】:
      mem_ptr = libc.malloc(ctypes.c_uint(size))
      

      显然是错误的。 malloc 的参数类型为 size_t

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2021-11-21
        • 1970-01-01
        • 2018-10-05
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多