我正在尝试运行一个 C 函数,该函数返回一个包含多个 int
的结构(目前)。
我的 C 源代码如下所示:
struct my_struct {
int i;
int j;
} ;
extern "C" struct my_struct struct_test(){
struct my_struct s;
s.i = 2;
s.j = 331;
return s;
}
对应的Makefile是这样的:
CXX=/usr/bin/g++
PYTHON=/usr/bin/ipython3 --colors Linux
CXXFLAGS=-Wall -fPIC -O3 -c
LDFLAGS=-Wall -shared -Wl,-soname,libfoo.so
TARGETS=mylib.so
all: mylib.so test
mylib.so: mylib.cpp
$(CXX) $(CXXFLAGS) -o mylib.o mylib.cpp
$(CXX) $(LDFLAGS) -o mylib.so mylib.o
test: mylib.so
$(PYTHON) ctypes_call_test.py
clean:
rm -f $(TARGETS)
Python 脚本在这里:
import ctypes
libname = './mylib.so'
class my_struct(ctypes.Structure):
_fields_ = [
("i", ctypes.c_int),
("j", ctypes.c_int),
]
mylib = ctypes.cdll.LoadLibrary(libname)
mylib.struct_test.argtypes=[]
mylib.struct_test.restype=ctypes.POINTER(my_struct)
ret = mylib.struct_test();
print('got return value')
print(ret.contents.i, ret.contents.j)
当我运行 Python 脚本时,它在 print()
语句之后立即崩溃。知道为什么会这样吗?
最佳答案
您在返回值中的结构上指定了一个指针,而它是结构本身。
将最后几行更改为:
mylib.struct_test.restype = my_struct # <=== no more pointer
ret = mylib.struct_test();
print('got return value')
print(ret.i, ret.j) # <=== remove "contents"
打印:
got return value
(2, 331)
关于Python 3 ctypes 调用具有返回结构的函数因段错误而失败,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50877184/