c++调用python接口作用是_利用Boost::Python实现C++调用python接口
利用Boost::Python實(shí)現(xiàn)C++調(diào)用python接口
2019年11月06日
閱讀數(shù):7
這篇文章主要向大家介紹利用Boost::Python實(shí)現(xiàn)C++調(diào)用python接口,主要內(nèi)容包括基礎(chǔ)應(yīng)用、實(shí)用技巧、原理機(jī)制等方面,希望對大家有所幫助。
Boost.Python能將C++的結(jié)構(gòu)體暴露給Python使用。可是在運(yùn)用Boost.Python時,卻遇到一個難題,
一、在C++定義一個新的結(jié)構(gòu)體struct?A
二、將此結(jié)構(gòu)體暴露給Python解釋器
三、現(xiàn)在在工程中生成結(jié)構(gòu)體A的對象,A?a。
四、但愿將a傳入Python解釋器進(jìn)行運(yùn)算,運(yùn)算的函數(shù)寫在某py文件中。
一直沒有辦法解決,但愿大蝦幫助解答。 python
這個問題就是在c++中調(diào)用py實(shí)現(xiàn)的接口函數(shù)。
相似c++代碼
struct?a
{
int?a?;
int?b;
};
a?temp;
GetPythonFunc(?&?temp?);?//調(diào)用python函數(shù),參數(shù)為必定結(jié)構(gòu)體的引用.
這個結(jié)構(gòu)體用boost能夠?qū)С鼋opython. 可是這個參數(shù)要怎么傳遞給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!
總結(jié)
以上是生活随笔為你收集整理的c++调用python接口作用是_利用Boost::Python实现C++调用python接口的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。
                            
                        - 上一篇: python语言三大基本控制结构_Pyt
 - 下一篇: flex布局_flex布局的 flex(