gpt4 book ai didi

Python ctypes : how to allocate output buffer for C function in callback

转载 作者:行者123 更新时间:2023-11-30 19:28:38 27 4
gpt4 key购买 nike

我将下一个回调作为 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 代码尝试写入分配的内存时,这两种变体都会导致段错误。请帮我解决这个问题

最佳答案

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

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

关于Python ctypes : how to allocate output buffer for C function in callback,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53701646/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com