我试图在IPython中执行C代码(使用ctype),但是每次调用C函数时,IPython都会崩溃。
环境
最小工作实例
文件test.c
int func(){
return 10;
}在命令行中编译:
gcc -shared -o test.dll -fPIC test.c在同一个目录中启动IPython,然后运行:
In [1]: import ctypes
...: lib = ctypes.CDLL("test.dll")
...: lib.func()
Out[1]: 10输出Out[1]是正确的,但是IPython在打印Out[1]: 10之后立即崩溃。(有时它会在打印Out[1]: 10之前崩溃)
问题
IPython支持类型吗?
若然,为何会出现上述问题?
如果不是这样的话,是否有办法在IPython/木星笔记本中使用ctype?
更新
CDLL更改为WinDLL;参见注释);没有工作。更新:问题解决
从TDM-GCC切换到明威-W64,这以某种方式解决了问题。
发布于 2021-04-27 03:49:06
正如在上面的评论中提到的,它很可能不是由于IPython,它没有不工作的理由。
尽管为了简化在IPython中使用c定义函数,您也可以尝试查看使用libffi的魔术原型包是如何工作的。它使(重新)定义函数稍微容易一些。
$ 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]: 3https://stackoverflow.com/questions/67249246
复制相似问题