2013-01-08 2 views
0

파이썬 및 ctypes를 사용하여 모터 제어 시스템을 함께 패치하려고하는데 필자가해야 할 일 중 하나는 텍스트 입력을 받아이를 8로 변환하는 것입니다. 비트 부호있는 정수.파이썬에서 문자열을 8 비트 부호있는 정수로 변환

다음은 내가 전화하려고 해요 함수에 대한 설명서입니다. 프로그램에 입력해야 할 텍스트가 'EPOS2'

이다

enter image description here

아래와 같이 데이터 타입 정의 ("숯 * '는 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) 
+2

그것은'char' 아니라, 그것의''의 char *입니다. 기술적으로 말하자면'char'에 대한 포인터이지만 일반적으로 Null Byte 또는 String으로 끝나는'chars '의 배열을 나타냅니다. 어떻게이 함수를 호출하려고합니까? 예제 코드는 정확히 무엇이 누락되었는지 알려줍니다. – FrankieTheKneeMan

+2

여기서'ctypes '의 사용법을 명확하게 설명해 주시겠습니까? 다른 라이브러리를 호출하고 그것을 사용하고 싶습니까? 아니면 실제로'struct' 모듈을 사용하여 구조체를 에뮬레이트 할 수 있습니까? –

+0

나는 현재 내가 가진 것을 넣는다. 바라기를 이것은 내가하려고하는 것에 대해 약간의 빛을 비춰줍니다. – Chris

답변

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] 

데이터 유형 정의에는 0으로 표시되지만이 아니라 char* 이니, 어떻게 처리해야할지 모르겠습니다.

2

사용자 인터페이스에는 C 문자열 인 char*이 필요합니다. 해당 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 값이 반환 값에 의해, 당신이 사용할 수있는 지적에 액세스하려면 :

VCS_OpenDevice.restype = POINTER(c_uint32) 
retval = VCS_OpenDevice(DeviceName,ProtocolStackName,InterfaceName,PortName) 
print retval.contents.value