【问题标题】:Convert a string to an 8-bit signed integer in python在python中将字符串转换为8位有符号整数
【发布时间】:2013-01-08 23:35:10
【问题描述】:

我正在尝试使用 python 和 ctypes 将电机控制系统拼凑在一起,我需要做的一件事是获取文本输入并将其转换为 8 位有符号整数。

以下是我尝试调用的函数的文档。应该输入到程序中的文本是'EPOS2'

数据类型定义如下图(注意'char*'相当于一个8位有符号整数)

那么如何将“EPOS2”转换为介于 -128 和 127 之间的值?

最终我想要做的是这样的:

import ctypes #import the module

lib=ctypes.WinDLL(example.dll) #load the dll

VCS_OpenDevice=lib['VCS_OpenDevice'] #pull out the function

#per the parameters below, each input is expecting (as i understand it) 
#an 8-bit signed integer (or pointer to an array of 8 bit signed integers, 
#not sure how to implement that)
VCS_OpenDevice.argtypes=[ctypes.c_int8, ctypes.c_int8, ctypes.c_int8, ctypes.c_int8]

#create parameters for my inputs
DeviceName ='EPOS2'
ProtocolStackName = 'MAXON SERIAL V2'
InterfaceName = 'USB'
PortName = 'USB0'


#convert strings to signed 8-bit integers (or pointers to an array of signed 8-bit integers)
#code goes here
#code goes here
#code goes here

#print the function with my new converted input parameters


print VCS_OpenDevice(DeviceName,ProtocolStackName,InterfaceName,PortName)

【问题讨论】:

  • 这不是char,而是char*。从技术上讲,它是指向char 的指针,但通常用于表示以空字节或字符串结尾的chars 数组。您如何尝试调用此函数?示例代码会让我们知道究竟缺少什么。
  • 你能澄清一下ctypes的用法吗?您是在调用另一个库并希望使用它来执行此操作,还是可以直接使用 struct 模块模拟一个结构?
  • 我把我目前所拥有的。希望这对我正在尝试做的事情有所启发。

标签: python ctypes signed unsigned-integer


【解决方案1】:

你可以使用ctypes:

>>> from ctypes import cast, pointer, POINTER, c_char, c_int
>>> 
>>> def convert(c):
...     return cast(pointer(c_char(c)), POINTER(c_int)).contents.value
... 
>>> map(convert, 'test string')
[116, 101, 115, 116, 32, 115, 116, 114, 105, 110, 103]

哪个(我刚刚发现)与ord 的输出相匹配:

>>> map(ord, 'test string')
[116, 101, 115, 116, 32, 115, 116, 114, 105, 110, 103]

虽然您的数据类型定义将其列为char,而不是char*,但我不确定您将如何处理。

【讨论】:

    【解决方案2】:

    您的界面采用 C 字符串 char*。等效的ctypes 类型是c_char_p。使用:

    import ctypes
    lib = ctypes.WinDLL('example.dll')
    VCS_OpenDevice = lib.VCS_OpenDevice
    VCS_OpenDevice.argtypes = [ctypes.c_char_p,ctypes.c_char_p,ctypes.c_char_p,ctypes.c_char_p]
    
    DeviceName ='EPOS2'
    ProtocolStackName = 'MAXON SERIAL V2'
    InterfaceName = 'USB'
    PortName = 'USB0'
    
    print VCS_OpenDevice(DeviceName,ProtocolStackName,InterfaceName,PortName)
    

    另外,WinDLL 通常只用于 Windows 系统 DLL。如果您的接口在 C 头文件中声明为__stdcall,则WinDLL 是正确的;否则,使用CDLL

    此外,您的返回码记录为DWORD*,这有点奇怪。为什么不DWORD?如果DWORD*是正确的,要访问返回值所指向的DWORD的值,可以使用:

    VCS_OpenDevice.restype = POINTER(c_uint32)
    retval = VCS_OpenDevice(DeviceName,ProtocolStackName,InterfaceName,PortName)
    print retval.contents.value
    

    【讨论】:

      猜你喜欢
      • 2013-06-08
      • 2021-10-06
      • 1970-01-01
      • 2014-02-20
      • 1970-01-01
      • 2011-04-17
      • 1970-01-01
      • 2011-04-21
      • 1970-01-01
      相关资源
      最近更新 更多