ctypes 和 C++ 中的输出不匹配
Output Mismatch in ctypes and C++
我有一个带有自定义类型变量的 dll,该变量是在将 ref 传递给 getstatus 函数后填充的。
C++:
#pragma pack(push, 1)
typedef struct Status_ {
unsigned char mode;
unsigned char state;
unsigned int info;
unsigned int errorCode;
unsigned char selected;
char id[25];
}Status;
#pragma pack(pop)
Status status = { 0 };
int ret = GetStatus(someid, &status)
Python:
class Status(Structure):
_fields_ = [("mode", c_ubyte),
("state", c_ubyte),
("info", c_uint),
("errorCode", c_uint),
("selected", c_ubyte),
("id", c_char * 25)]
status = Status()
getStatus = dll.GetStatus
getStatus.argtypes = [c_int, POINTER(Status)]
getStatus.restype = c_int
ret = getStatus(someid, byref(status));
我不确定哪里出了问题,但我在 C++ 和 python 中得到了不同的状态字段值。
编辑:添加了 dll 代码中缺少的 pragma 预处理器
如果 header 中有指示,请确保设置包装;否则,将在不与自然地址边界对齐的字段之间添加额外的填充字节。例如,4 字节的“info”参数通常会在它之前添加两个字节的填充,因此它在结构中的偏移量将是 4 的倍数。
添加 _pack_ = 1
以删除所有打包字节。
class Status(Structure):
_pack_ = 1
_fields_ = (("mode", c_ubyte),
("state", c_ubyte),
("info", c_uint),
("errorCode", c_uint),
("selected", c_ubyte),
("id", c_char * 25))
status = Status()
getStatus = dll.GetStatus
getStatus.argtypes = c_int, POINTER(Status)
getStatus.restype = c_int
ret = getStatus(someid, byref(status))
我有一个带有自定义类型变量的 dll,该变量是在将 ref 传递给 getstatus 函数后填充的。
C++:
#pragma pack(push, 1)
typedef struct Status_ {
unsigned char mode;
unsigned char state;
unsigned int info;
unsigned int errorCode;
unsigned char selected;
char id[25];
}Status;
#pragma pack(pop)
Status status = { 0 };
int ret = GetStatus(someid, &status)
Python:
class Status(Structure):
_fields_ = [("mode", c_ubyte),
("state", c_ubyte),
("info", c_uint),
("errorCode", c_uint),
("selected", c_ubyte),
("id", c_char * 25)]
status = Status()
getStatus = dll.GetStatus
getStatus.argtypes = [c_int, POINTER(Status)]
getStatus.restype = c_int
ret = getStatus(someid, byref(status));
我不确定哪里出了问题,但我在 C++ 和 python 中得到了不同的状态字段值。
编辑:添加了 dll 代码中缺少的 pragma 预处理器
如果 header 中有指示,请确保设置包装;否则,将在不与自然地址边界对齐的字段之间添加额外的填充字节。例如,4 字节的“info”参数通常会在它之前添加两个字节的填充,因此它在结构中的偏移量将是 4 的倍数。
添加 _pack_ = 1
以删除所有打包字节。
class Status(Structure):
_pack_ = 1
_fields_ = (("mode", c_ubyte),
("state", c_ubyte),
("info", c_uint),
("errorCode", c_uint),
("selected", c_ubyte),
("id", c_char * 25))
status = Status()
getStatus = dll.GetStatus
getStatus.argtypes = c_int, POINTER(Status)
getStatus.restype = c_int
ret = getStatus(someid, byref(status))