Skip to content Skip to sidebar Skip to footer

Writing Cython Extension: How To Access A C Struct Internal Data From Python?

Disclaimer: I took the following example from the Python Cookbook (O'Reilly). Let's say I have the following simple struct: typedef struct { double x,y; } Point; with a function

Solution 1:

I was initially a little confused about this question since it seemed to have no Cython content (sorry the editing mess resulting from that confusion).

The Python cookbook uses Cython in a very odd way which I wouldn't recommend following. For some reason it wants to use PyCapsules which I have never seen used before in Cython.

# tell Cython about what's in "points.h"# (this does match the cookbook version)

cdefexternfrom"points.h"
    ctypedefstruct Point:
        double x
        double y

    double distance(Point *, Point *)

# Then we describe a class that has a Point member "pt"
cdefclass Py_Point:
    cdefPoint pt

    def__init__(self,x,y):
        self.pt.x = x
        self.pt.y = y

    # define properties in the normal Python way    @propertydefx(self):
        return self.pt.x

    @x.setterdefx(self,val):
        self.pt.x = val

    @propertydefy(self):
        return self.pt.y

    @y.setterdefy(self,val):
        self.pt.y = val

defpy_distance(Py_Point a, Py_Point b):
    return distance(&a.pt,&b.pt) # get addresses of the Point members

You can then compile it and use it from Python as

from whatever_your_module_is_called import *

# create a couple of points
pt1 = Py_Point(1.3,4.5)
pt2 = Py_Point(1.5,0)

print(pt1.x, pt1.y) # access the membersprint(py_distance(pt1,pt2)) # distance between the two

In fairness to the Python Cookbook it then gives a second example that does something very similar to what I've done (but using a slightly older property syntax from when Cython didn't support the Python-like approach). So if you'd have read a bit further you wouldn't have needed this question. But avoid mixing Cython and pycapsules - it isn't a sensible solution and I don't know why they recommended it.

Post a Comment for "Writing Cython Extension: How To Access A C Struct Internal Data From Python?"