0

Python と ctypes を使用してモーター制御システムにパッチを適用しようとしています。必要なことの 1 つは、テキスト入力を取得して 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

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
于 2013-01-11T02:31:24.417 に答える
2

使用できます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*、それをどのように処理するかわかりません。

于 2013-01-08T23:40:42.787 に答える