我將下一個回調作為 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
。
添加回答
舉報
0/150
提交
取消