【发布时间】:2021-08-12 16:45:22
【问题描述】:
我一直在使用 ctypes 将一些 C 代码 [FANUC FOCAS 库] 移植到 Python。
在我必须移植的最复杂的结构之一中,我无法捕获所有变量的值,也无法找出原因。
在 C 中(来自 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
我真的不明白为什么 acts.data 没有返回预期值。
有人可以帮我解决这个问题吗?非常感谢。
【问题讨论】:
-
使用
speed = ODBSpeed_T(),r = fwl.cnc_rdspeed(h, ctypes.c_short(-1), ctypes.pointer(speed)) -
感谢您对@CristiFati 的评论。不幸的是,它并没有解决问题。也许,这是机器配置而不是 python ctypes 的东西。感谢分享
-
机会渺茫。现在是什么行为?请注意,您现在必须使用:speed.acts.data.
-
行为保持不变:speed.acts.data = 0,此时实际值不应为零。