【问题标题】:How to create a C struct from Python using ctypes?如何使用 ctypes 从 Python 创建 C 结构?
【发布时间】:2021-04-30 06:30:25
【问题描述】:

我有与this 问题类似的问题。我基本上是在尝试使用 ctypes 从 Python 创建 C 结构。

在 C 中我有:

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);
}

在 Python 中我有:

    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)

目前这会输出一堆指针:

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

我怎样才能让这个输出返回我输入的数字,即

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

【问题讨论】:

    标签: python c struct ctypes language-interoperability


    【解决方案1】:

    问题是c_int64。 将其更改为c_int32 后,它工作正常。 你可以从C端把c_int64当作long

    另外,你可以这样做

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

    【讨论】:

    • 我明白了:AttributeError: 'Point' object has no attribute 'contents'
    • @CiaranWelsh 啊...然后,p['x']p['y']。你试过了吗?
    • @CiaranWelsh pptr.contents.x 可能有效。我认为...
    • 最好不要依赖 c 内置类型来获取等式 C 端的字长。 stdint.h 有 int32_t/int64_t 和其他用于此目的。
    • 另外,ctypesc_int 到并行 C int。使用匹配类型。
    猜你喜欢
    • 1970-01-01
    • 2014-01-28
    • 1970-01-01
    • 1970-01-01
    • 2014-08-29
    • 2012-07-19
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多