簡體   English   中英

如何將Boost模塊從C ++導入python?

[英]How to import boost module from C++ to python?

以下是我要導入的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 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>

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM