如何使用Cython创建stand

2024-04-26 17:52:28 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一个Python脚本,我将脚本重命名为.pyx文件。我想把这段代码编译成一个标准的dll文件。

我在this document中看到Cython将创建一个dll文件,但我只得到一个pyd。

我有mingw并尝试使用命令python setup.py build --compiler=mingw32编译脚本我的代码(只是一个hello世界):

def init():
    return "hello world"

有什么想法吗?谢谢


Tags: 文件代码命令脚本hello标准thisdocument
2条回答

所以首先要做的是重命名 文件到helloworld.pyx。现在我们需要 创建setup.py,它就像 python Makefile(有关详细信息 见汇编)。你的setup.py应该 看起来像:

from distutils.core import setup
from distutils.extension import Extension

from Cython.Distutils import build_ext
    setup(
        cmdclass = {'build_ext': build_ext},
        ext_modules = [Extension("helloworld",
    ["helloworld.pyx"])] )

用这个来建立你的Cython文件 使用命令行选项:

$ python setup.py build_ext --inplace

会在本地留下一个文件 unix中名为helloworld.so的目录 或Windows中的helloworld.dll。

现在到 使用此文件:启动python 解释器并简单地导入 它是一个普通的python模块:

Is a *.pyd file the same as a DLL?

Yes, .pyd files are dll’s, but there are a few differences. If you have a DLL named foo.pyd, then it must have a function PyInit_foo(). You can then write Python “import foo”, and Python will search for foo.pyd (as well as foo.py, foo.pyc) and if it finds it, will attempt to call PyInit_foo() to initialize it. You do not link your .exe with foo.lib, as that would cause Windows to require the DLL to be present.

Note that the search path for foo.pyd is PYTHONPATH, not the same as the path that Windows uses to search for foo.dll. Also, foo.pyd need not be present to run your program, whereas if you linked your program with a dll, the dll is required. Of course, foo.pyd is required if you want to say import foo. In a DLL, linkage is declared in the source code with __declspec(dllexport). In a .pyd, linkage is defined in a list of available functions.

Modifying Python’s Search PathAbsolute and Relative Imports

相关问题 更多 >