2

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

1 Answer 1

2

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)
Sign up to request clarification or add additional context in comments.

7 Comments

I get this: AttributeError: 'Point' object has no attribute 'contents'
@CiaranWelsh Ah... Then, p['x'] and p['y']. Have you tried them?
@CiaranWelsh pptr.contents.x may work. I think...
Best not to rely on c builtin types for word length on the C-side of the equation. stdint.h has int32_t/int64_t and others for this purpose.
Also, ctypes has c_int to parallel C int. Use matching types.
|

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.