Skip to main content
 首页 » 编程设计

python之在 Ctypes 中传递结构

2024年11月01日8fff_TT

我一直在尝试在 Ctypes 中传递一个结构。但是函数调用抛出格式错误。

这是我的 C 函数:

typedef struct Point2Struct {    
    double x, y; 
    } Point2; 
 
Point2 test(Point2 k) 
{ 
  return k; 
} 

python调用如下:

class Point2(Structure): 
    _fields_ = [('x',c_double),('y',c_double)] 
 
lib.test.argtypes=[Point2] 
lib.test.restype=Point2 
p = Point2(1.1, 2.2) 
 
g = lib.test(p) 
 
print g.x, g.y 

当我通过 CDLL 调用该函数时,我得到:

ValueError: Procedure called with not enough arguments (4 bytes missing) or wrong calling convention 

使用 WinDLL,我得到:

ValueError: Procedure probably called with too many arguments (16 bytes in excess) 

我在 Windows 7 下使用 (Mingw) gcc 将 C 代码编译成 DLL。

 gcc -shared -o test.dll test.o 

我还尝试使用 .so 文件:

gcc -shared -Wl,-soname,test-o test.so -fPIC test.c 

但是我得到了同样的错误。

我做错了什么?我应该使用任何特定选项进行编译吗?

请您参考如下方法:

为了处理大于 8 字节的聚合返回,MinGW 和 Microsoft 的编译器都隐式地传递了一个指向调用者本地内存的指针。看起来你的 gcc 版本默认在 callee 中弹出这个指针。然而,ctypes/libffi 是用 Visual Studio 构建的,并且需要 Microsoft 的约定,它在调用者中处理这个问题。这就是它提示缺少 4 个字节的原因。

如果您使用的是 gcc 4.6+,则有一个 function attribute启用 Microsoft 的约定:

callee_pop_aggregate_return (number)

On 32-bit i?86-- targets, you can control by those attribute for aggregate return in memory, if the caller is responsible to pop the hidden pointer together with the rest of the arguments - number equal to zero -, or if the callee is responsible to pop hidden pointer - number equal to one. The default i386 ABI assumes that the callee pops the stack for hidden pointer.

似乎 gcc 4.7 使用 Microsoft 约定作为 Windows 目标的默认值:

Note, that on 32-bit i386 Windows targets the compiler assumes that the caller pops the stack for hidden pointer.

我在 Windows 上使用 gcc 4.6.3 进行测试,它仍然使用“默认 i386 ABI”。设置函数属性解决了问题:

Point2 test(Point2 k) 
    __attribute__((callee_pop_aggregate_return(0))); 

当然,您的里程可能会有所不同。更好的是,如果您可以控制规范,我认为只使用通过引用传递的显式输出参数会更简单。