I am trying to execute C code in IPython (using ctypes), but IPython crashes every time a C function is called.
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)
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?
CDLL
to WinDLL
; see comments); did not work.Switched from TDM-GCC to Mingw-w64, and this somehow solves the problem.
As mentioned in above comment it is likely not due to IPython there is no reasons for it to not work.
Though to simplify using c-defined function in IPython, you can also try to look at how the cffi_magic prototype package that use libffi works. It makes it slightly easier to (re)define function.
$ ipython
Python 3.8.5 | packaged by conda-forge | (default, Sep 16 2020, 17:43:11)
Type 'copyright', 'credits' or 'license' for more information
IPython 7.23.0.dev -- An enhanced Interactive Python. Type '?' for help.
In [1]: import cffi_magic
In [2]: %%cffi int func(int, int);
...: int func(int a, int b){
...: return a+b;
...: }
clang-10: warning: -Wl,-export_dynamic: 'linker' input unused [-Wunused-command-line-argument]
ld: warning: -pie being ignored. It is only used when linking a main executable
In [3]: func(1, 2)
Out[3]: 3
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With