Related to this: python ctypes array of structs
I have a struct of struct in C. I am creating one of them dynamically and would like to access it in python using ctypes.
Below is an example:
foo.c
#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);
}
foo.h
#ifndef FOO_H
#define FOO_H
typedef struct POINT
{
int x;
int y;
}Point;
typedef struct MYSTRUCT
{
int a;
double b;
Point p[5];
Point * dynamic_p;
}MyStruct;
void setIt();
MyStruct * retIt();
#endif
After compiling with gcc -shared -o test.so -fPIC foo.c
test.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
I can access the p array without a problem.
The last line returns a segmentation fault. I understand that I must be accessing an illegal part of memory. But I have tries all types of combination and cannot get it to work.
Really would really appreciate any light on the subject.
EDIT: Posted the wrong python code last and forgot the dynamic_p feild
Cheers
AttributeError: 'Point' object has no attribute 'contents'