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?
functhat raises the error, or is it the code that sets up the arg values?func. I've also tried calling it from the library directly as inclibrary.myfunc(c1, i, c2)but encounter the same issue.WinDLLis used for 32-bit DLLs with__stdcallcalling convention.CDLLis normally what you need for default__cdeclcalling convention. On 64-bit it doesn't matter as there is only one calling convention.