Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Does IPython support ctypes?

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 to WinDLL; see comments); did not work.

Update: problem solved

Switched from TDM-GCC to Mingw-w64, and this somehow solves the problem.

like image 734
inverse Avatar asked Nov 06 '22 02:11

inverse


1 Answers

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
like image 142
Matt Avatar answered Nov 13 '22 17:11

Matt