我一直在使用ctypes将一些C代码[FANUC FOCAS库]移植到Python
在我必须移植的最复杂的结构之一中,我无法捕获所有变量的值,也无法找出原因
中的(摘自FANUC的fwlib32.h)
typedef struct speedelm {
long data;
short dec;
short unit;
short disp;
char name;
char suff;
} SPEEDELM ;
typedef struct odbspeed {
SPEEDELM actf;
SPEEDELM acts;
} ODBSPEED ;
FWLIBAPI short WINAPI cnc_rdspeed( unsigned short, short, ODBSPEED * );
然后,对于Python,我写道:
import ctypes
class SpeedElmT(ctypes.Structure):
pass
SpeedElmT._fields_ = [
("data", ctypes.c_long),
("dec", ctypes.c_short),
("unit", ctypes.c_short),
("disp", ctypes.c_short),
("name", ctypes.c_char_p),
("suff", ctypes.c_char_p)
]
class ODBSpeed_T(ctypes.Structure):
_fields_ = [
("actf", SpeedElmT),
("acts", SpeedElmT),
]
# import library
fwl = ctypes.cdll.LoadLibrary("/fwlib_path/")
fwl.cnc_rdspeed.argtypes = ctypes.c_ushort, ctypes.c_short, ctypes.POINTER(ODBSpeed_T)
fwl.cnc_rdspeed.restype = ctypes.c_short
在C中运行它的示例(可在inventcom.net上找到)
#include "fwlib32.h"
void example( void )
{
ODBSPEED speed;
short ret = cnc_rdspeed(h, -1, &speed);
if(!ret) {
printf("%c = %d\n", speed.actf.name, speed.actf.data);
printf("%c = %d\n", speed.acts.name, speed.acts.data);
}
}
而且,在Python中,我尝试了
speed = ctypes.pointer(ODBSpeed_T())
r = fwl.cnc_rdspeed(h, ctypes.c_short(-1), speed)
if r == 0:
print(speed[0].actf.data) # This one returns the correct value
print(speed[0].acts.data) # Zero when not Zero
我真的不明白为什么会起作用。数据不会返回预期值
有人能帮我吗?非常感谢
错误是C代码有
char
而不是char*
。Python中的字段必须是c_char
而不是c_char_p
,因此结构大小是错误的以下是具有相同接口的测试DLL:
test.py:
输出:
相关问题 更多 >
编程相关推荐