Python CTypes:如何在回调中为C函数分配输出缓冲区

时间:2018-12-10 08:05:09

标签: python c python-2.7 memory ctypes

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

Foo

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

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

还有

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

但是当试图写入分配的内存时,这两种变体均导致C代码中的分段错误。 请帮我修复它

2 个答案:

答案 0 :(得分:0)

mem_ptr = libc.malloc(ctypes.c_uint(size))

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

答案 1 :(得分:0)

现在可以使用了

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))