0

我正在尝试使用 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)
4

2 回答 2

2

您的界面采用char*C 字符串。等效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。如果你的接口是__stdcall在 C 头文件中声明的,WinDLL是正确的;否则,使用CDLL.

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

VCS_OpenDevice.restype = POINTER(c_uint32)
retval = VCS_OpenDevice(DeviceName,ProtocolStackName,InterfaceName,PortName)
print retval.contents.value
于 2013-01-11T02:31:24.417 回答
2

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.

于 2013-01-08T23:40:42.787 回答