在python中将字符串转换为8位有符号整数

2024-10-01 00:20:44 发布

您现在位置:Python中文网/ 问答频道 /正文

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

下面是我要调用的函数的文档。应输入程序的文本为“EPOS2”

enter image description here

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

enter image description here

那么如何将“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)

Tags: thetointegersanherebitcodevcs
2条回答

{cd1>字符串是你的接口。等效的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值,可以使用:

^{pr2}$

您可以使用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的输出相匹配:

^{pr2}$

尽管您的数据类型定义将其列为char,而不是char*,所以我不确定您将如何处理它。在

相关问题 更多 >