pythonctypes:如何为callb中的C函数分配输出缓冲区

2024-09-28 22:29:53 发布

您现在位置:Python中文网/ 问答频道 /正文

我将下一个回调作为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代码在试图写入分配的内存时出现分段错误。 拜托,帮我修一下


Tags: 代码sizecallbackctypestmpbuffintlibc
2条回答
mem_ptr = libc.malloc(ctypes.c_uint(size))

显然是错的。malloc的参数属于size_t类型。你知道吗

现在起作用了:

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

相关问题 更多 >