Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
60 views
in Technique[技术] by (71.8m points)

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

question from:https://stackoverflow.com/questions/65901925/how-to-create-a-c-struct-from-python-using-ctypes

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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)

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...