问题
I'm trying to patch together a motor control system using python and ctypes and one of the things I need to do is take an text input and convert it to an 8-bit signed integer.
Below is the documentation for the function I'm trying to call. The text that should be input into the program is 'EPOS2'
The data type definition is as shown below (note that 'char*' equates to an 8-bit signed integer)
So How do I convert 'EPOS2' to a value between -128 and 127?
Ultimately what I'm trying to do is something like this:
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)
回答1:
You could use 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]
Which (as I just found out) matches the output of ord
:
>>> map(ord, 'test string')
[116, 101, 115, 116, 32, 115, 116, 114, 105, 110, 103]
Although your data type definitions list it as a char
, not a char*
, so I'm not sure how you'd handle that.
回答2:
Your interface takes char*
which are C strings. The equivalent ctypes
type is c_char_p
. Use:
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)
Also, WinDLL
is normally only needed for Windows system DLLs. If your interfaces are declared __stdcall
in the C header file, WinDLL
is correct; otherwise, use CDLL
.
Additionally, your return code is documented as a DWORD*
, which is a bit strange. Why not DWORD
? If DWORD*
is correct, to access the value of the DWORD pointed to by the return value, you can use:
VCS_OpenDevice.restype = POINTER(c_uint32)
retval = VCS_OpenDevice(DeviceName,ProtocolStackName,InterfaceName,PortName)
print retval.contents.value
来源:https://stackoverflow.com/questions/14225915/convert-a-string-to-an-8-bit-signed-integer-in-python