我正在尝试将 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
>>>
所以有几个问题:
是否可以导入一个dll
在Python中without使用ctypes?该教程似乎表明确实如此,但没有提供有关将 dll 导入 python 的正确方法的详细信息。
我需要哪些文件以及在哪里?看来我只需要dll
我的 python shell 的工作目录中来自 Visual Studio 的文件,但这显然不适合我。
为什么我不能打电话World
通过ctypes?
一些更重要的细节:我使用的是 Windows 7 64 位、Python 3.5.2 64 位和带有 Boost 1.61 的 Visual Studio 2015。