Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/c/66.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
如何使用ctypes从Python创建C结构?_Python_C_Struct_Ctypes_Language Interoperability - Fatal编程技术网

如何使用ctypes从Python创建C结构?

如何使用ctypes从Python创建C结构?,python,c,struct,ctypes,language-interoperability,Python,C,Struct,Ctypes,Language Interoperability,我有一个类似的问题。我基本上是在尝试使用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; }

我有一个类似的问题。我基本上是在尝试使用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
21474836484
-8646857406049613808
我如何让这个输出返回我输入的数字,即

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

2365277332448
4.
5.

问题是
c\u 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”对象没有属性“contents”
@CiaranWelsh Ah。。。然后,
p['x']
p['y']
。你试过了吗?@CiaranWelsh
pptr.contents.x
可能有用。我认为…最好不要依赖c内置类型来计算公式c端的字长。stdint.h有int32\u t/int64\u t和其他用于此目的的类型。而且,
ctypes
c\u int
到并行c
int
。使用匹配类型。