Python 3 ctypes 调用具有返回结构的函数因段错误而失败

标签 python c python-3.x ctypes

我正在尝试运行一个 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/

相关文章:

c - 在堆上使用 unsigned

c - IAR 编译器 : using struct with function pointers, 映射文件显示结构中声明的所有函数,无论是否使用函数

python - 将整数写入文本文件

python unittest2 - 将测试方法名称暴露给设置方法

python - 列表理解的意外输出

python - 多处理 Python 库中的慢速数据结构

c - 在 scanf 中多次使用相同的整数

python - usn 解析器将类似 json 的数据转换为 pandas 数据帧

python-3.x - Pandas 插入备用空白行

python - 在 python 中杀死标准输出中断 get_line_buffer()