Ctypes access violation error

0

I'a trying to port an old rfid library implemented in oldest VB to a python script.

here's the vb code:

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

I am not absolute new to the ctypes thing, ok I tried this:

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)

and got: OSError: exception: access violation reading 0x00000033

I read the dokumentation on cType datetyes handling but I can't see the right way

the descript of the functions:

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 )
python
ctypes
asked on Stack Overflow Feb 17, 2018 by bluelemonade • edited Feb 17, 2018 by bluelemonade

1 Answer

0

c_wchar is equivalent to C's wchar_t not char*, so c_wchar('3') is passing the ASCII value 0x0033 instead of a valid pointer to char, which matches the address of the access violation.

With ctypes it is best to be explicit about types by specifying the argument types and return type, then just pass a Python byte string for any input char* parameter (which really should be const char* to make this clear). Output parameters require a writable string and should be allocated with 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') 
answered on Stack Overflow Feb 17, 2018 by Mark Tolonen

User contributions licensed under CC BY-SA 3.0