hanno
hanno

Reputation: 6513

ctypes and array of structs

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.

Upvotes: 2

Views: 2605

Answers (1)

Mark Tolonen
Mark Tolonen

Reputation: 177406

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

Upvotes: 3

Related Questions