如何使用ctypes从Python创建C结构?
我有一个类似的问题。我基本上是在尝试使用ctypes从Python创建C结构 在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; }
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']
。你试过了吗?@CiaranWelshpptr.contents.x
可能有用。我认为…最好不要依赖c内置类型来计算公式c端的字长。stdint.h有int32\u t/int64\u t和其他用于此目的的类型。而且,ctypes
有c\u int
到并行cint
。使用匹配类型。