如何将整数解释为浮点数

Nes*_* W. 5 dll ctypes python-3.x

我正在尝试使用 C# 编写的 DLL 与激光器进行通信。我使用 ctypes 模块成功加载了 DLL 函数。我想使用的函数有一个如下所示的声明:

LONG LJV7IF_GetStorageData( LONG lDeviceId, 
                            LJV7IF_GET_STORAGE_REQ* pReq,
                            LJV7IF_STORAGE_INFO* pStorageInfo,
                            LJV7IF_GET_STORAGE_RSP* pRsp, 
                            DWORD* pdwData, 
                            DWORD dwDataSize );
Run Code Online (Sandbox Code Playgroud)

我想通过双字指针 pdwData 访问数据。激光器通过如下结构发送其存储的数据:

Bytes |  Meaning  |   Types
 0-3  |   time    |    dword          
  4   |  judgment |    byte
  5   | meas info |    byte
 ...  |    ...    |    ... 
 8-11 |   data    |    float
Run Code Online (Sandbox Code Playgroud)

这就是我使用该功能的方式:

self.dll = WinDLL( "LJV7_IF.dll" )
self._getStoredData = self.dll.LJV7IF_GetStorageData
self._getStoredData.restype = c_int32
self._getStoredData.argstypes = [ c_int32,
                                  POINTER( GET_STORAGE_REQ ),
                                  POINTER( STORAGE_INFO ),
                                  POINTER( GET_STORAGE_RSP ),
                                  POINTER( c_uint32 ),
                                  c_uint32 ]
dataSize = 132
dataBuffer = c_uint32 * ( dataSize / 4 )
outputData_p = POINTER( c_uint32 )( dataBuffer() )
self._getStoredData( deviceID,
                     byref( myStruct ),
                     byref( storageInfo ),
                     byref( storageResponse ),
                     outputData_p ),
                     dataSize )
Run Code Online (Sandbox Code Playgroud)

为了简洁起见,没有对 myStruct、storageInfo 和 storageResponse 进行详细说明(它们在其他 DLL 函数调用中使用,并且它们似乎工作得很好)。

我的问题是当我尝试访问时outputData_p[ 2 ],python 返回一个 int,比如 1066192077。这正是我问他的。但我希望该 int 被解释/转换为浮点数,它应该是 1.1 或类似的东西(不记得确切的值)。使用任一方法将其转换为浮动都不起作用(我得到 1066192077.00 )hex() -> bytes() -> struct.unpack( )。我能做些什么 ??

Ery*_*Sun 5

注意:如果您在搜索如何将整数转换为单精度浮点数时到达这里,请忽略此答案的其余部分,仅使用 JF Sebastian 评论中的代码。它使用 struct 模块而不是 ctypes,后者更简单并且始终可用,而 ctypes 可以选择包含在 Python 的标准库中:

import struct

def float_from_integer(integer):
    return struct.unpack('!f', struct.pack('!I', integer))[0]

assert float_from_integer(1066192077) == 1.100000023841858
Run Code Online (Sandbox Code Playgroud)

您可以使用 ctypes 方法将数组解释为不同的类型from_buffer。一般来说,您可以将任何具有可写缓冲区接口的对象传递给此方法,而不仅仅是 ctypes 实例——例如bytearrayNumPy 数组。

例如:

import struct

def float_from_integer(integer):
    return struct.unpack('!f', struct.pack('!I', integer))[0]

assert float_from_integer(1066192077) == 1.100000023841858
Run Code Online (Sandbox Code Playgroud)

它仍然是相同的字节,只是重新解释为两个 8 字节双精度数:

>>> from ctypes import *
>>> int_array = (c_int * 4)(1, 2, 3, 4)
>>> n_doubles = sizeof(int_array) // sizeof(c_double)
>>> array_t = c_double * n_doubles
>>> double_array = array_t.from_buffer(int_array)
Run Code Online (Sandbox Code Playgroud)

由于该数组是通过调用创建的from_buffer,而不是调用from_buffer_copy,它实际上是一个与原始数组共享相同缓冲区的视图。例如,如果将最后 2 个整数移到前面,则 中的值double_array也会交换:

>>> bytes(double_array)
b'\x01\x00\x00\x00\x02\x00\x00\x00\x03\x00\x00\x00\x04\x00\x00\x00'
>>> double_array[:]
[4.2439915824e-314, 8.4879831653e-314]
Run Code Online (Sandbox Code Playgroud)

请注意,您的示例代码有一个拼写错误。定义函数参数类型的属性名称是argtypes,而不是argstypes

>>> int_array[:] = [3, 4, 1, 2]
>>> double_array[:]
[8.4879831653e-314, 4.2439915824e-314]
Run Code Online (Sandbox Code Playgroud)

定义此原型并不是绝对必要的,但建议这样做。from_param它使 ctypes在调用函数时为每个参数调用相应的方法。如果没有原型,默认参数处理接受 ctypes 实例并自动将字符串转换为char *orwchar_t *并将整数转换为 Cint值;否则它会引发ArgumentError.

您可以按如下方式定义打包(即没有对齐填充)数据记录:

self._getStoredData.argstypes = [ c_int32,
                    ^^^^^^^^^
Run Code Online (Sandbox Code Playgroud)

下面是一个示例类,它将通用数据参数类型定义为,POINTER(c_byte)并将结果作为由设备实例确定的记录数组返回。显然,这只是该类实际应该如何定义的要点,因为我对这个 API 几乎一无所知。

class LaserData(Structure):
    _pack_ = 1
    _fields_ = (('time',      c_uint),
                ('judgement', c_byte),
                ('meas_info', c_byte * 3),
                ('data',      c_float))
Run Code Online (Sandbox Code Playgroud)

例如:

class LJV7IF(object):
    # loading the DLL and defining prototypes should be done
    # only once, so we do this in the class (or module) definition.
    _dll = WinDLL("LJV7_IF")
    _dll.LJV7IF_Initialize()

    _dll.LJV7IF_GetStorageData.restype = c_long
    _dll.LJV7IF_GetStorageData.argtypes = (c_long,
                                           POINTER(GET_STORAGE_REQ),
                                           POINTER(STORAGE_INFO),
                                           POINTER(GET_STORAGE_RSP),
                                           POINTER(c_byte),
                                           c_uint)

    def __init__(self, device_id, record_type):
        self.device_id = device_id
        self.record_type = record_type

    def get_storage_data(self, count):
        storage_req = GET_STORAGE_REQ()
        storage_info = STORAGE_INFO()
        storage_rsp = GET_STORAGE_RSP()
        data_size = sizeof(self.record_type) * count
        data = (c_byte * data_size)()
        result = self._dll.LJV7IF_GetStorageData(self.device_id,
                                                 byref(storage_req),
                                                 byref(storage_info),
                                                 byref(storage_rsp),
                                                 data,
                                                 data_size)
        if result < 0: # assume negative means an error.
            raise DeviceError(self.device_id) # an Exception subclass.
        return (self.record_type * count).from_buffer(data)
Run Code Online (Sandbox Code Playgroud)