I am converting a file from python2 to python3 that calls a C function using the ctypes
module.
The below minimal example works in python2, however raises the following error in python3 (3.11)
OSError: exception: access violation writing 0x00000000000094E0
// mydll.c
#include <stdio.h>
void myfunc(char* c, int i, char* c2) {
printf("Hello World");
}
int main() {
return 0;
}
# foo.py
import ctypes
import sys
PY3 = sys.version_info.major == 3
if PY3:
clibrary = ctypes.WinDLL("mydll.dll", winmode=1)
else:
clibrary = ctypes.WinDLL("mydll.dll")
prototype = ctypes.CFUNCTYPE(None, ctypes.c_char_p, ctypes.c_int, ctypes.c_char_p)
c1 = (ctypes.c_char * 512)()
i = ctypes.c_int(0)
c2 = (ctypes.c_char * (600 * 8))()
func = prototype(("myfunc", clibrary))
func(c1, i, c2)
I think this has something to do with unicode vs bytes representation of strings between python versions. From what I gather this looks like dereferencing a null pointer or something of that nature. I've tried using ctypes.create_string_buffer()
but encounter the same error.
I expect the same code to work in both python2 and python3. What is causing the python3 error?