Ctypes访问冲突错误

时间:2018-02-17 17:58:12

标签: python ctypes

我试图将最旧VB中实现的旧rfid库移植到python脚本。

这里是vb代码:

dim hport as integer 
dim hreader as integer 
hport=FECOM_OpenPort("1") 
if hport>0 then 
   FECOM_SetPortPara(hport,"Baud","38400") 
   FECOM_SetPortPara(hport,"Frame","8E1") 
   hreader =FEISC_NewReader(hport)
   and so on

我对ctypes事情并不是绝对新手,好吧我试过了:

import ctypes
from ctypes import *
feisc = ctypes.cdll.FeIsc
fecom = ctypes.cdll.FeCom
c_port = c_wchar('3')
#c_port = c_wchar('3')
hport = fecom.FECOM_OpenPort(c_port)

得到了: OSError:异常:访问冲突读取0x00000033

我在cType日期处理上阅读了dokumentation,但我看不出正确的方法

功能描述:

int FECOM_OpenPort( char* cPortNr )
int FECOM_ClosePort( int iPortHnd )
int FECOM_GetPortPara( int iPortHnd, char* cPara, char* cValue )
int FECOM_SetPortPara( int iPortHnd, char* cPara, char* cValue )

1 个答案:

答案 0 :(得分:0)

c_wchar相当于C wchar_t而不是char*,因此c_wchar('3')传递的是ASCII值0x0033而不是有效的指向char的指针,它匹配访问冲突的地址。

使用ctypes时,最好通过指定参数类型和返回类型来明确表示类型,然后只为任何输入 char*参数传递Python字节字符串(真的应该const char*来明确这一点。输出参数需要可写字符串,并应使用create_string_buffer()分配。

from ctypes import *

fecom = CDLL('FeCom')

# int FECOM_OpenPort( char* cPortNr )
fecom.FECOM_OpenPort.argtypes = c_char_p,
fecom.FECOM_OpenPort.restype = c_int

# int FECOM_ClosePort( int iPortHnd )
fecom.FECOM_ClosePort.argtypes = c_int,
fecom.FECOM_ClosePort.restype = c_int

# int FECOM_GetPortPara( int iPortHnd, char* cPara, char* cValue )
fecom.FECOM_GetPortPara.argtypes = c_int,c_char_p,c_char_p
fecom.FECOM_GetPortPara.restype = c_int

# int FECOM_SetPortPara( int iPortHnd, char* cPara, char* cValue )
fecom.FECOM_SetPortPara.argtypes = c_int,c_char_p,c_char_p
fecom.FECOM_SetPortPara.restype = c_int

hport = FECOM_OpenPort(b'1') 
if hport > 0:
   FECOM_SetPortPara(hport,b'Baud',b'38400') 
   FECOM_SetPortPara(hport,b'Frame',b'8E1')