1

I'm trying to access the C-funtions with the following prototypes through ctypes library in python

HandleT OpenFile (const char *FName, ResultT *ReturnCode);
ResultT GetItem (HandleT handle, void **data, int *len);

ResultT is an enum.

Let's say the python code i'm using is:

FILE = "E:/LogData/!d1fx/D1F1"


clib = ctypes.CDLL('c_libs\RAWRD64.dll')

data = ctypes.c_void_p(0)
datalen = ctypes.c_int()
result = ctypes.c_int()
handle = ctypes.c_void_p()


handle = clib.OpenFile(FILE, ctypes.byref(result))

#debug output
print ("handle: %d, ret: %d" %(handle, result.value))

clib.GetItem(handle, ctypes.byref(data), ctypes.byref(datalen))

#debug output
print ("result: %d" % (result.value))
print ("data: %s, len: %d" %(data.value, datalen.value))

With python 2.7 on a Windows 7 machine this code works. I've been migrating to a Windows 10 machine now and in the same step trying to port this code to python 3.8.

The first issue I encounterd was, that openFile() returned, that it cannot open the file. This could be fixed by adding an encoding to the file name.

handle = clib.OpenFile(FILE.encoding("ANSI"), ctypes.byref(result))

However, GetItem() now raises the following exception:

handle: 389636160, ret: 0
Traceback (most recent call last):
  File ".\test_clib.py", line 19, in <module>
    clib.GetItem(handle, ctypes.byref(data), ctypes.byref(datalen))
OSError: exception: access violation reading 0x0000000017396040

Why does this code raise an exception with pyhton 3.8 and work with 2.7? Is there any difference in how DLLs are treated with ctypes?

Flirog
  • 11
  • 1
  • Does this answer your question? [Python ctypes: Access violation](https://stackoverflow.com/questions/48461739/python-ctypes-access-violation) – Joe Apr 27 '20 at 09:49
  • On Windows, ctypes uses win32 structured exception handling to prevent crashes from general protection faults when functions are called with invalid argument values. https://docs.python.org/3.4/library/ctypes.html#calling-functions – Joe Apr 27 '20 at 09:53
  • https://stackoverflow.com/questions/7256283/differences-in-ctypes-between-python-2-and-3 – Joe Apr 27 '20 at 09:54
  • Most problems can be traced to skipping setting `.argtypes` and `.restype` for your functions. Fix that first and come back if it still doesn't work. Did you also switch to a 64-bit OS? `ctypes` defaults to returning c_int, so handle could be a truncated 64-bit pointer. Setting `clib.OpenFile.restype = c_void_p` would fix that. – Mark Tolonen Apr 27 '20 at 20:50
  • [\[SO\]: C function called from Python via ctypes returns incorrect value (@CristiFati's answer)](https://stackoverflow.com/questions/58610333/c-function-called-from-python-via-ctypes-returns-incorrect-value/58611011#58611011). – CristiFati Nov 03 '21 at 19:04

0 Answers0