将结构传递给ctypes中的dll(freepie)

时间:2018-12-20 00:03:01

标签: python c python-3.x struct ctypes

Freepie有一个dll文件,可用于将数据传递到程序中。这是我这样做的脚本:

import time
import ctypes
from ctypes import byref, c_int, POINTER


class freepie_io_6dof_data(ctypes.Structure):
    __fields__ = [
        ("Yaw", ctypes.c_float()),
        ("Pitch", ctypes.c_float()),
        ("Roll", ctypes.c_float()),
        ("X", ctypes.c_float()),
        ("Y", ctypes.c_float()),
        ("Z", ctypes.c_float())]

q = ctypes.CDLL("E:\\Program Files (x86)\\FreePIE\\freepie_io.dll")  # Load DLL
slots = q.freepie_io_6dof_slots()
data = freepie_io_6dof_data()
data.Y = ctypes.c_float(0)
q.freepie_io_6dof_write.argtypes = [c_int, c_int, POINTER(freepie_io_6dof_data)]
while True:
    q.freepie_io_6dof_write(0, 1, byref(data))
    print(data)
    time.sleep(0.5)

但是,当freepie获得数据时,每次我运行该程序时,它将显示为不同的数字,通常类似于6.34523234E-36。预期输出为0,我在哪里出错?

1 个答案:

答案 0 :(得分:0)

主代码中的错别字导致错误的性能。将__fields__更改为_fields_并从ctypes.c_float中删除括号后,代码可以正常工作!

这是最终代码:

import time
import ctypes
from ctypes import byref, c_int, POINTER


class freepie_io_6dof_data(ctypes.Structure):
    _fields_ = [
        ("Yaw", ctypes.c_float),
        ("Pitch", ctypes.c_float),
        ("Roll", ctypes.c_float),
        ("X", ctypes.c_float),
        ("Y", ctypes.c_float),
        ("Z", ctypes.c_float)]

q = ctypes.CDLL("E:\\Program Files (x86)\\FreePIE\\freepie_io.dll")  # Load DLL
slots = q.freepie_io_6dof_slots()
data = freepie_io_6dof_data()
data.Y = ctypes.c_float(0)
q.freepie_io_6dof_write.argtypes = [c_int, c_int, POINTER(freepie_io_6dof_data)]
while True:
    q.freepie_io_6dof_write(0, 1, byref(data))
    print(data)
    time.sleep(0.5)