pythoncstructctypeslanguage-interoperability

How to create a C struct from Python using ctypes?


I have a similar problem to this question. I'm basically trying to create C structs from Python using ctypes.

In C I have:

typedef struct Point {
    int x;
    int y;
} Point ;

Point* makePoint(int x, int y){
    Point *point = (Point*) malloc(sizeof (Point));
    point->x = x;
    point->y = y;
    return point;
}

void freePoint(Point* point){
    free(point);
}

While in Python I have:

    class Point(ct.Structure):
        _fields_ = [
            ("x", ct.c_int64),
            ("y", ct.c_int64),
        ]


    lib = ct.CDLL("SRES.dll")

    lib.makePoint.restype = ct.c_void_p

    pptr = lib.makePoint(4, 5)
    print(pptr)

    p = Point.from_address(pptr)
    print(p)
    print(p.x)
    print(p.y)

Currently this outputs a bunch of pointers:

2365277332448
<__main__.Point object at 0x00000226D2C55340>
21474836484
-8646857406049613808

How can I instead make this output return the numbers I put in, i.e.

2365277332448
<__main__.Point object at 0x00000226D2C55340>
4
5


Solution

  • The problem was c_int64. After changing it to c_int32, it works fine. You may take c_int64 as long from C side.

    Additionally, you can do

    lib.makePoint.restype = ct.POINTER(Point)
    p = lib.makePoint(4, 5)
    print(p.contents.x)
    print(p.contents.y)