【问题标题】:How to import boost module from C++ to python?如何将boost模块从C++导入python?
【发布时间】:2018-12-28 12:58:49
【问题描述】:

以下是我要导入的 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()

当我尝试运行脚本时,我没有在终端得到“hello,zoo”作为输出。我在哪里做错了?

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

导入:未授权zoo' @ error/constitute.c/WriteImage/1028. ./visit_zoo.py: line 3: syntax error near unexpected token(' ./visit_zoo.py:第 3 行:`assert 'hello' in dir(zoo)'

【问题讨论】:

    标签: python c++ boost boost-python


    【解决方案1】:

    你没有像我一样忘记指出脚本应该由 Python 运行吗?

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

    #!/usr/bin/env python2
    

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

    $ python <filename>
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-07-12
      • 2015-04-02
      • 1970-01-01
      相关资源
      最近更新 更多