【发布时间】:2020-03-25 04:48:31
【问题描述】:
我尝试使用 ctypes 为 C 库编写 Python 包装器。 到目前为止,我有:
C.h
typedef struct
{
int erorrCode;
char * Key;
} A;
#ifdef __cplusplus
extern "C" {
#endif
EXPORT void __stdcall DestroyA(A &input);
#ifdef __cplusplus
}
#endif
C.cpp
EXPORT void __stdcall DestroyA(A &input)
{
delete []input.Key;
}
Python.py
import sys
import ctypes
class A(ctypes.Structure):
_fields_ = [
("erorrCode", ctypes.c_int),
("Key", ctypes.c_char_p)]
try:
libapi = ctypes.cdll.LoadLibrary('./lib.so')
except OSError:
print("Unable to load RAPI library")
sys.exit()
DestroyA = libapi.DestroyA
libapi.DestroyA.argtypes = [ctypes.POINTER(A)]
libapi.DestroyA.restype = None
a = A(1,b'random_string')
DestroyA(ctypes.byref(a)) #!!!here is segmentation fault
那么,我该如何解决分段错误错误?
注意:只要有办法在 Python 端修复它,我就无法更改 C++ 端的代码。
【问题讨论】:
-
为什么你的函数是__stdcall?
-
您确定要拨打
DestroyA吗?因为您在这里a = A(1,b'random_string')在Python 中分配c_char_p。因此 Python 应该为其分配的对象处理内存。这意味着您的库函数不管理它应该“删除”的地址并给您一个分段错误。 -
另一件事是您正试图调用一个标记为
__stdcall的函数。但是您的库加载为 CDLLctypes.cdll.LoadLibrary,这意味着 dll 导出应该有__cdecl(请参阅此处 docs.python.org/3/library/…)。
标签: python struct ctypes dynamic-library