在IronPython解释器中导入*.pyd库

2 投票
2 回答
1091 浏览
提问于 2025-04-16 06:40

根据这个例子,我创建了一个小的 hello.pyd 库文件,文件内容在这个问题的最后部分。

当我进入 Python 解释器时,我得到了以下结果:

D:\test\build\lib.win32-2.6>C:\Python26\python.exe
Python 2.6.6 (r266:84297, Aug 24 2010, 18:46:32) [MSC v.1500 32 bit (Intel)] on win32
Type "help", "copyright", "credits" or "license" for more information.
>>> import hello
>>> hello.say_hello("Greg")
Hello Greg!
>>>

但是在使用 IronPython 的解释器时却出现了错误:

D:\test\build\lib.win32-2.6>"C:\Program Files (x86)\IronPython 2.7\ipy.exe"
IronPython 2.7 Alpha 1 (2.7.0.1) on .NET 4.0.30319.1
Type "help", "copyright", "credits" or "license" for more information.
>>> import hello
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
ImportError: No module named hello
>>>

我该如何让 ipy 解释器接受这个用 C++ 编译的库呢?


hellomodule.cpp

#include "C:\Python26\include\Python.h"

static PyObject* say_hello(PyObject* self, PyObject* args)
{
    const char* name;

    if (!PyArg_ParseTuple(args, "s", &name))
        return NULL;

    printf("Hello %s!\n", name);

    Py_RETURN_NONE;
}

static PyMethodDef HelloMethods[] =
{
     {"say_hello", say_hello, METH_VARARGS, "Greet somebody."},
     {NULL, NULL, 0, NULL}
};

PyMODINIT_FUNC

inithello(void)
{
     (void) Py_InitModule("hello", HelloMethods);
}

setup.py

from distutils.core import setup, Extension

module1 = Extension('hello', sources = ['hellomodule.cpp'])

setup (name = 'PackageName',
        version = '1.0',
        description = 'This is a demo package',
        ext_modules = [module1])

编译方式如下

python setup.py build -cmingw32

2 个回答

0

这个问题很可能是因为你的 .pyd 库没有放在 IronPython 能找到的正确位置。因为你使用的是 Python,而不是 IronPython 的安装工具,所以它可能是在 PYTHONPATH 里建立和设置的,而不是 IronPython 需要的地方。

解决办法有两个:a.) 更改 IronPython 的路径,或者 b.) 在 IronPython 的路径下重新构建。

3

你可以试试 Ironclad,不过最近这个项目更新得不多。

撰写回答