使用ctypes从Python中的C函数返回的结构中访问数据

我知道这个问题已经得到了处理,但我找不到任何对我有用的东西,所以我猜我的问题与其他问题略有不同。

基本上,我所做的是使用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代码中检查了结构是否存在以及结构的每个字段是否存在,并且其中包含正确的数据。

谢谢。

假设你有一个像这样的C结构:

 typedef struct _servParams { unsigned short m_uServPort; char m_pInetAddr[MAX_LENGTH_OF_IP_ADDRESS]; } ServerParams_t; 

要在ctypes中使用它,你应该创建一个这样的包装器:

 class ServerParams_t(Structure): _fields_ = [ ("m_uServPort", c_ushort), ("m_pInetAddr", (c_char * 16)) ] 

稍后在python中,您可以使用以下代码段:

 servParams = ServerParams_t() servParams.m_uServPort = c_ushort(int(port)) servParams.m_pInetAddr = ip.encode() 

如果需要按值传递它,只需将servParams变量传递给api即可。 如果需要传递指针,请使用byref(servParams)