相关疑难解决方法(0)

在C++中嵌入Python并从C++代码调用方法

我尝试将Python脚本嵌入到我的C++程序中.在阅读了有关嵌入和扩展的一些内容之后,我了解了如何打开自己的python脚本以及如何将一些整数传递给它.但现在我有点不明白如何解决我的问题.我必须做两件事,从C++调用Python函数并从我的嵌入式Python脚本调用C++函数.但我不知道从哪里开始.我知道我必须编译.so文件以将我的C++函数暴露给Python,但这不是我能做的,因为我必须嵌入我的Python文件并使用C++代码控制它(我必须使用脚本语言,使一些逻辑易于编辑).

那么,有什么方法可以做这两件事吗?从C++调用Python函数并从Python调用C++函数?

这是我的C++代码

#include <Python.h>
#include <boost/python.hpp>
using namespace boost::python;


// <----------I want to use this struct in my python file---------
struct World
{
    void set(std::string msg) { this->msg = msg; }
    std::string greet() { return msg; }
    std::string msg;
};


// Exposing the function like its explained in the boost.python manual
// but this needs to be compiled to a .so to be read from the multiply.py
BOOST_PYTHON_MODULE(hello)
{
    class_<World>("World")
        .def("greet", &World::greet)
        .def("set", &World::set)
    ;
}
// <---------------------------------------------------------------


int …
Run Code Online (Sandbox Code Playgroud)

c++ python boost-python

3
推荐指数
1
解决办法
8074
查看次数

标签 统计

boost-python ×1

c++ ×1

python ×1