I am trying to execute C code in IPython (using ctypes), but IPython crashes every time a C function is called.
Environment
- Windows 10 (64bit)
- Python 3.8.5 64bit
- GCC 9.1.0 (tdm-gcc)
Minimum working example
File test.c
:
int func(){
return 10;
}
Compile in commandline:
gcc -shared -o test.dll -fPIC test.c
Start IPython in the same directory, then run:
In [1]: import ctypes
...: lib = ctypes.CDLL("test.dll")
...: lib.func()
Out[1]: 10
The output Out[1]
is correct, but IPython crashes immediately after Out[1]: 10
is printed. (sometimes it crashes before Out[1]: 10
is printed)
Question
Does IPython support ctypes?
If so, why the aforementioned problem occured?
If not so, is there a workaround to use ctypes in IPython/Jupyter Notebook?
Updates
- Tried the same code on WSL (on the same machine); IPython did not crash.
- Tried Tim Roberts's solution (changing
CDLL
toWinDLL
; see comments); did not work.
Update: problem solved
Switched from TDM-GCC to Mingw-w64, and this somehow solves the problem.
stdcall
linkage. Usectypes.windll("test.dll")
. Mismatches in the calling conventions cause crashes after the function returns, because the stack isn't properly cleaned up.