gpt4 book ai didi

Cython:使其他 Cython 模块可以访问外部 C 函数

转载 作者:行者123 更新时间:2023-11-30 16:51:54 24 4
gpt4 key购买 nike

如果我在外部库中有一个 C 函数 void foo(),我可以在 module1.pyx 中执行它:

cdef extern from "fooHeader.h":
void foo();
...
foo()

但是,我可以在不使用包装函数的情况下将此函数公开给其他 Cython 模块吗?

例如,使用module1.pxd:

cdef extern void foo()

不使该函数在module2.pyx中可用:

from module1 cimport foo
foo()

由于 undefined symbol 错误而中止。

最佳答案

典型的方法是创建一个包装器,因为当您向 Python 代码公开此类函数时,您通常希望拦截类型等。在我的脑海中,完成您所追求的任务的最简单方法可能是使用 Cython 的 包含文件 工具, .pxi文件:

https://cython.readthedocs.io/en/latest/src/reference/language_basics.html#include-file

链接中的片段:

How do I use it?

  • Include the .pxi file with an include statement like: include "spamstuff.pxi"
  • The include statement can appear anywhere in your Cython file and at any indentation level
  • The code in the .pxi file needs to be rooted at the “zero” indentation level.
  • The included code can itself contain other include statements.

所以你可以输入 cdef extern <...>放入.pxi文件并将其包含在您的所有用户中。

(旁注:我不记得是否可以通过 .pxd 接口(interface)文件公开外部模块。这可能也可以,但我还没有检查过。)

关于Cython:使其他 Cython 模块可以访问外部 C 函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41526101/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com