[转载] python字符串转有符号数字_在python中将字符串转换为8位带符号整数

参考链接: Python中将十进制转换为字符串

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)

 解决方案

 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

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值