c++调用python接口作用是_利用Boost::Python实现C++调用python接口
利用Boost::Python實現C++調用python接口
2019年11月06日
閱讀數:7
這篇文章主要向大家介紹利用Boost::Python實現C++調用python接口,主要內容包括基礎應用、實用技巧、原理機制等方面,希望對大家有所幫助。
Boost.Python能將C++的結構體暴露給Python使用。可是在運用Boost.Python時,卻遇到一個難題,
一、在C++定義一個新的結構體struct?A
二、將此結構體暴露給Python解釋器
三、現在在工程中生成結構體A的對象,A?a。
四、但愿將a傳入Python解釋器進行運算,運算的函數寫在某py文件中。
一直沒有辦法解決,但愿大蝦幫助解答。 python
這個問題就是在c++中調用py實現的接口函數。
相似c++代碼
struct?a
{
int?a?;
int?b;
};
a?temp;
GetPythonFunc(?&?temp?);?//調用python函數,參數為必定結構體的引用.
這個結構體用boost能夠導出給python. 可是這個參數要怎么傳遞給python代碼呢? ios
最后在python?mailist找到答案 c++
--------------------------------------------------
#include?
#include?
using?namespace?boost::python;
class?World
{
public:
void?set(std::string?msg)?{?this->msg?=?msg;?}
std::string?greet()?{?return?msg;?}
std::string?msg;
};
typedef?boost::shared_ptr?world_ptr;
BOOST_PYTHON_MODULE(hello)
{
class_("World")
.def("greet",?&World::greet)
.def("set",?&World::set)
;
register_ptr_to_python();
}
int?main(int?argc,?char?*argv[])
{
Py_Initialize();
world_ptr?worldObjectPtr?(new?World);
worldObjectPtr->set("Hello?from?C++!");
try?{
inithello();
PyRun_SimpleString("import?hello");
object?module(handle<>(borrowed(PyImport_AddModule("__main__"))));
object?dictionary?=?module.attr("__dict__");
dictionary["pyWorldObjectPtr"]?=?worldObjectPtr;
PyRun_SimpleString("pyWorldObjectPtr.set('Hello?from?Python!')");
}?catch?(error_already_set)?{
PyErr_Print();
}
std::cout?<greet():?"?<greet()?<<
std::endl;
Py_Finalize();
return?0;
}
--------------------------------------------------
Output:
worldObjectPtr->greet():?Hello?from?Python!
總結
以上是生活随笔為你收集整理的c++调用python接口作用是_利用Boost::Python实现C++调用python接口的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: python语言三大基本控制结构_Pyt
- 下一篇: 正则化的通俗解释_干货|深度学习中的正则