1

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

3
  • Have you try: pyMS.contents.dynamic_p[0].contents.x since dynamic_p[0] is a pointer? Commented May 21, 2015 at 18:42
  • Well spotted, added the wrong python script. Sorry about that @eryksun. I tried the contents line @DanielYuen, but it returns AttributeError: 'Point' object has no attribute 'contents' Commented May 22, 2015 at 10:59
  • What is the problem you are facing now ? I am able to run the test.py script and also able to print the last line - print(pyMS.contents.dynamic_p[0].x). It prints value of 88 for me. I do not get any segmentation fault. Commented Sep 3, 2017 at 21:56

0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.