如何将提升模块从C++导入到python

How to import boost module from C++ to python?

本文关键字:C++ 导入 python 模块      更新时间:2023-10-16

以下是我要导入的c ++代码。

#include <boost/python.hpp>
#include <string>
/*
 * This is the C++ function we write and want to expose to Python.
 */
const std::string hello() {
    return std::string("hello, zoo");
}
/*
 * This is a macro Boost.Python provides to signify a Python extension module.
 */
BOOST_PYTHON_MODULE(zoo) {
    // An established convention for using boost.python.
    using namespace boost::python;
    // Expose the function hello().
    def("hello", hello);
}

以下代码是 python 脚本。

import zoo     # In zoo.cpp we expose hello() function, and it now exists 
                  in the zoo module.
assert 'hello' in dir(zoo)   # zoo.hello is a callable.
assert callable(zoo.hello)   # Call the C++ hello() function from Python.
print zoo.hello()

当我尝试运行脚本时,我在终端上没有收到"你好,动物园"作为输出。我哪里犯了错误?

以下是我收到的错误消息:

导入:未授权zoo' @ error/constitute.c/WriteImage/1028. ./visit_zoo.py: line 3: syntax error near unexpected token ('./visit_zoo.py:第 3 行:"在 dir(zoo)中断言'hello'"

你不是忘记指出脚本应该由 Python 运行吗,就像我一样?

您可以在脚本文件的标头中包含 python 可执行文件:

#!/usr/bin/env python2

并使文件可执行或使用 Python 调用脚本:

$ python <filename>