为了账号安全,请及时绑定邮箱和手机立即绑定

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

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

精慕HU 2021-09-11 20:26:33
我将下一个回调作为 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)。我尝试了 2 种方法。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 代码中的分段错误。请帮我修复它
查看完整描述

2 回答

?
12345678_0001

TA贡献1802条经验 获得超5个赞

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

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


查看完整回答
反对 回复 2021-09-11
  • 2 回答
  • 0 关注
  • 244 浏览
慕课专栏
更多

添加回答

举报

0/150
提交
取消
微信客服

购课补贴
联系客服咨询优惠详情

帮助反馈 APP下载

慕课网APP
您的移动学习伙伴

公众号

扫描二维码
关注慕课网微信公众号