python - 如何调用需要指向具有 ctypes 的结构的指针的 c 函数?

标签 python pointers structure ctypes

我面临以下问题。我用 C 语言编写了以下内容:

#include <stdio.h>
typedef struct {
double *arr;
int length;
} str;

void f(str*);

int main (void){
   double x[3] = {0.1,0.2,0.3};
   str aa;
   aa.length = 3;
   aa.arr = x;
   f(&aa);
   return 0;
}

void f(str *ss){
   int i;
   printf("%d\n",ss->length);
   for (i=0; i<ss->length; i++) {
      printf("%e\n",ss->arr[i]);
   }
}

如果我将其编译为可执行文件,它可以正常工作。我收到:

 3
 0.1
 0.2
 0.3

应该如此。从上面的 C 代码构建共享库“pointertostrucCtypes.so”后,我在 python 中调用函数 f,如下所示:

ptrToDouble = ctypes.POINTER(ctypes.c_double)
class pystruc (ctypes.Structure):
   _fields_=[
             ("length",ctypes.c_int),
             ("arr",ptrToDouble)
            ]
aa = pystruc()
aa.length = ctypes.c_int(4)
xx = numpy.arange(4,dtype=ctypes.c_double)
aa.arr = xx.ctypes.data_as(ptrToDouble)
myfunc = ctypes.CDLL('pointertostrucCtypes.so')
myfunc.f.argtypes = [ctypes.POINTER(pystruc)]

myfunc.f(ctypes.byref(aa))

它总是导致打印出任意整数,然后它给我一个段错误。因为长度不合适。有人知道我在这里做错了什么吗?

最佳答案

您的字段颠倒了。尝试:

class pystruc (ctypes.Structure):
    _fields_=[
             ("arr",ptrToDouble)
             ("length",ctypes.c_int),
            ]

关于python - 如何调用需要指向具有 ctypes 的结构的指针的 c 函数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7040576/

相关文章:

python - 通过分析邻居像素强度绘制磁盘

python - 二进制流中 `open` 和 `io.BytesIO` 之间的区别

python - Tkinter:在框架类中创建多个框架

c - 为什么我的 C 代码不能使用指针和结构体工作?

backbone.js - 您如何构建您的 Backbone + RequireJS 应用程序?

python - 困惑 - 在Python中从字典列表中获取具有多个关联值的唯一键

c - 在C中保存一个指针地址

c - string 没有以 NULL 结尾,但仍然表现正常,为什么?

c++ - 预编译头文件中的错误 C2512?

c - 我无法让我的C程序输出到文件