【问题标题】:Does IPython support ctypes?IPython 支持 ctypes 吗?
【发布时间】:2021-04-25 02:34:56
【问题描述】:

我正在尝试在 IPython 中执行 C 代码(使用 ctypes),但每次调用 C 函数时 IPython 都会崩溃。

环境

  • Windows 10(64 位)
  • Python 3.8.5 64 位
  • GCC 9.1.0 (tdm-gcc)

最小的工作示例

文件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] 是正确的,但在打印Out[1]: 10 后IPython 立即崩溃。 (有时它会在打印 Out[1]: 10 之前崩溃)

问题

IPython 支持 ctypes 吗?

如果有,为什么会出现上述问题?

如果不是这样,是否有在 IPython/Jupyter Notebook 中使用 ctypes 的解决方法?

更新

  • 在 WSL 上尝试了相同的代码(在同一台机器上); IPython 没有崩溃。
  • 尝试了 Tim Roberts 的解决方案(将 CDLL 更改为 WinDLL;参见 cmets);没用。

更新:问题已解决

从 TDM-GCC 切换到 Mingw-w64,这以某种方式解决了问题。

【问题讨论】:

  • 您确定您的问题是特定于 IPython 的吗?如果您在常规 Python 解释器中尝试相同的测试,它是否有效?
  • 我在 Ubuntu 20.04 上使用 Python 3.8.5 和 gcc 9.3.0 并且无法重现。您显示的代码在我的交互式解释器中运行良好。
  • @JosephSible-ReinstateMonica 是的,ctypes 在普通脚本中工作正常。
  • 您的库可能正在使用stdcall 链接构建。使用ctypes.windll("test.dll")。调用约定不匹配会导致函数返回后崩溃,因为堆栈没有正确清理。
  • UPD:从 TDM-GCC 切换到 Mingw-w64,问题解决了。

标签: python jupyter-notebook ipython ctypes


【解决方案1】:

正如上面评论中提到的,它可能不是由于 IPython,它没有理由不工作。

虽然为了简化在 IPython 中使用 c 定义的函数,你也可以尝试看看使用 libffi 的 cffi_magic 原型包是如何工作的。它使(重新)定义函数变得稍微容易一些。

  $ 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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2015-03-10
    • 2015-12-14
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-01-24
    • 2021-03-19
    • 2015-02-15
    相关资源
    最近更新 更多