2

I'd like to read an array of structs defined in a C library using ctypes and python.

The C struct is simply

struct particle {
  double x;
  double y;
}

I have a function that returns a pointer to an array of structs:

struct particle* getParticles();

In python I define

class Particle(Structure):
    _field_ = [("x", c_double),("y", c_double)]

Then I'm trying to parse the returned pointer from python, but seem to be doing something wrong:

getp = libparticles.getParticles
getp.restype = POINTER(Particle)
particles = getp()

particles is of type LP_Particle, which seems to make sense. But the values (e.g. particles[0].x) are garbage.

2
  • 2
    How are you initializing libparticles? It helps to post a fully functional example that illustrates the problem. My guess is the function uses "C" calling convention and you've initialized as "stdcall" or vice versa. Commented Sep 15, 2014 at 3:17
  • How are you supposed to know the length of the array? Commented Sep 15, 2014 at 3:20

1 Answer 1

3

Here's a working example for Windows DLL with default "C" calling convention. Without a working, complete example of your code and an example of the error you get it's difficult to tell where you went wrong. One observation is _fields_ was spelled _field_ in your code.

C source

struct particle { double x,y; };

__declspec(dllexport) struct particle* getParticles()
{
    static struct particle p[3] = {1.1,2.2,3.3,4.4,5.5,6.6};
    return p;
}

Python

from ctypes import *

class Particle(Structure):
    _fields_ = [("x", c_double),("y", c_double)]

getp = cdll.x.getParticles
getp.restype = POINTER(Particle)
particles = getp()
for i in range(3):
    print(particles[i].x,particles[i].y)

Output

1.1 2.2
3.3 4.4
5.5 6.6
Sign up to request clarification or add additional context in comments.

2 Comments

You were right about the initialization being the problem.
Of course, just another example of no working, complete example. It wasn't usable code.

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.