与此相关:python ctypes array of structs
我想在一个cython结构中动态地创建一个cython结构。在
下面是一个例子:
食品公司
#include <stdlib.h>
#include <stdio.h>
#include <string.h>
#include "foo.h"
MyStruct * ms;
void setIt()
{
ms = (MyStruct *)(calloc(1, sizeof(MyStruct)));
ms->a = 10;
ms->b = 99.99;
ms->dynamic_p = (Point *)(calloc(2, sizeof(Point)));
int i;
for(i=0; i<5; i++)
{
ms->p[i].x = i*5;
ms->p[i].y = i*10;
}
for(i=0; i<2; i++)
{
ms->dynamic_p[i].x = i+88;
ms->dynamic_p[i].y = i+88;
}
}
MyStruct * retIt()
{
return ms;
}
void main()
{
setIt();
printf("a: %d\n", ms->a);
printf("p[0].x: %d\n", ms->p[3].x);
printf("dynamic_p[0].y: %d\n", ms->dynamic_p[0].y);
}
食物
^{pr2}$在用gcc-shared-o编译之后测试.so-fPIC食品公司
在测试.py在
import ctypes
class Point(ctypes.Structure):
_fields_ = [('x', ctypes.c_int), ('y', ctypes.c_int)]
class MyStruct(ctypes.Structure):
_fields_ = [('a', ctypes.c_int), ('b', ctypes.c_double), ('p', Point*5), ('dynamic_p', ctypes.POINTER(Point))]
simulator = ctypes.cdll.LoadLibrary('your/path/to/test.so')
simulator.retIt.restype = ctypes.POINTER(MyStruct)
simulator.setIt()
pyMS = simulator.retIt()
pyMS.contents.dynamic_p[0].x
我可以毫无问题地访问p数组。在
最后一行返回分段错误。我知道我一定是在访问一个非法的内存部分。但我尝试过各种组合,但都没能成功。在
我真的很感激你能告诉我这个问题。在
编辑:最后发布了错误的python代码,但忘记了动态\u p feld
干杯
目前没有回答
相关问题 更多 >
编程相关推荐