无法在 python 中导入自定义 DLL

2024-01-17

我正在尝试将 C++ 类公开给 pythonboost::python,所以我正在经历本教程 http://www.boost.org/doc/libs/1_61_0/libs/python/doc/html/tutorial/tutorial/exposing.html。我创建了一个视觉工作室.dll项目,源代码如下:

#include <boost/python.hpp>
using namespace boost::python;

struct World
{
    void set(std::string msg) { this->msg = msg; }
    std::string greet() { return msg; }
    std::string msg;
};

BOOST_PYTHON_MODULE(hello)
{
    class_<World>("World")
        .def("greet", &World::greet)
        .def("set", &World::set)
    ;
}

我将它构建为 64 位 dll。本教程的下一步说:

在这里,我们编写了一个 C++ 类包装器,它公开了成员函数greet 和set。现在,将我们的模块构建为共享库后,我们可以在 Python 中使用我们的 World 类。下面是一个 Python 会话示例:

>>> import hello
>>> planet = hello.World()
>>> planet.set('howdy')
>>> planet.greet()
'howdy'

但是,在同一目录中启动 python 并输入import hello I get

>>> import hello
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
ImportError: No module named 'hello'
>>>

我尝试将“dll”文件重命名为hello.dll,并且还复制every输出文件 (dll, exp, ilk, lib, and pdb) to %PYTHONPATH%\DLLs,但我仍然无法将模块导入到 python 中。

很多谷歌搜索让我发现本文 http://wolfprojects.altervista.org/articles/dll-in-c-for-python/推荐我使用ctypes导入dll。这让我加载dll,但我仍然无法调用“World”类。例如:

>>> import ctypes
>>> mydll = ctypes.cdll.LoadLibrary("hello")
>>> mydll
<CDLL 'hello', handle 7fef40a0000 at 0x775ba8>
>>> hello = mydll.World()
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "C:\Program Files\Python35\lib\ctypes\__init__.py", line 360, in __getatt
r__
    func = self.__getitem__(name)
  File "C:\Program Files\Python35\lib\ctypes\__init__.py", line 365, in __getite
m__
    func = self._FuncPtr((name_or_ordinal, self))
AttributeError: function 'World' not found
>>>

所以有几个问题:

  1. 是否可以导入一个dll在Python中without使用ctypes?该教程似乎表明确实如此,但没有提供有关将 dll 导入 python 的正确方法的详细信息。

  2. 我需要哪些文件以及在哪里?看来我只需要dll我的 python shell 的工作目录中来自 Visual Studio 的文件,但这显然不适合我。

  3. 为什么我不能打电话World通过ctypes?

一些更重要的细节:我使用的是 Windows 7 64 位、Python 3.5.2 64 位和带有 Boost 1.61 的 Visual Studio 2015。


事实上,我在发布问题后不久就找到了答案。谢谢这篇博文 http://mmmovania.blogspot.com/2013/01/running-c-code-from-python-using.html我发现只需重命名hello.dll to hello.pyd就足够了。通过更多的谷歌搜索,我think that ctypes仅适用于 C DLL,不适用于 C++,并且not与助推!要点是boost::python,是为了消除对ctypes的需要并使DLL与python兼容。因此,回答我自己的所有问题:

  1. 可以,但是必须有一个.pyd扩大。

  2. 你只需要编译后的dll文件和boost_python_vc140...dll(可能会有所不同)。然而,正如我所说,dll文件必须重命名。

  3. 因为 ctypes 不是加载 a 的正确工具boost::python dll!

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

无法在 python 中导入自定义 DLL 的相关文章

随机推荐