【发布时间】:2017-08-25 14:13:54
【问题描述】:
我知道该主题已经过治疗,但我没有找到任何适合我的方法,所以我想我的问题与其他问题略有不同。
我所做的基本上是使用 ctypes 将 C 函数包装到 python 代码中。 我的目标是在 C 函数中计算一些量,将它们存储到单个结构中,然后在 Python 中返回结构,我可以在其中读取结构中的所有不同数据。
所以:
为了在 python 中定义我的结构,我使用:
class BITE(ctypes.Structure):
_fields_ = [
("lum", ctypes.c_int),
("suce", ctypes.c_int)
]
我是这样编译的:
sub.call(["gcc","-shared","-Wl,-install_name,ex.so","-o","ex.so","-fPIC","ex.c"])
lum = ctypes.CDLL('ex.so')
lum = lum.lum
我这样声明参数和结果类型:
lum.restype = ctypes.POINTER(BITE)
lum.argtypes = [ctypes.POINTER(ctypes.c_float),ctypes.c_int,ctypes.POINTER(ctypes.c_float),ctypes.c_int,ctypes.POINTER(ctypes.c_float),ctypes.POINTER(ctypes.c_float),ctypes.c_int,ctypes.POINTER(ctypes.c_float),ctypes.c_int,ctypes.POINTER(ctypes.c_float),ctypes.POINTER(ctypes.c_float),ctypes.POINTER(ctypes.c_float),ctypes.POINTER(ctypes.c_float),ctypes.c_float,ctypes.c_float,ctypes.c_float,ctypes.c_float,ctypes.c_float]
然后,我在python代码中调用C函数“lum”
out = lum(all the different variables needed)
问题从这里开始。我有我的结构,但无法读取存储在每个字段中的数据。
我找到的部分解决方案是:
out = out[0]
但是,在做的时候
print(out.suce)
我有一个分段错误 11。不知道为什么。我试图了解如何使用 create_string_buffer,但我并不真正了解它是如何工作的以及它应该做什么。此外,我尝试将其用作黑匣子,但仍然没有任何效果。
我还尝试了其他线程中提到的其他解决方案,例如使用 out.contents 或类似的东西,但它没有 .contents 属性。也不是 out.suce.value,这也是我在绝望的研究中看到的东西。
当然,我在 C 代码中检查了结构存在,结构的每个字段都存在,并且其中包含正确的数据。
谢谢。
【问题讨论】:
-
提供minimal reproducible example。如果我们无法重现问题或至少无法查看实际代码,则无法确定您做错了什么。
标签: c python-3.x ctypes