在C++中运行 python 对象

Run python object in C++

本文关键字:python 对象 运行 C++      更新时间:2023-10-16

我只是有一个关于在C++中运行python对象的问题。 让我在下面的示例中解释我想做什么。

int main () {
// as you know, the python object has its member variables etc, and 
// I want it to be initialized only once
py = python_object();   
while (1) {
// here, I am hoping to call a member function from the object continously
// and get a return value. 
int abc = py.get_num(); 
if (abc < 0) break;
do_something_in_my_cpp_code();
}

}

我在这里谈论的python对象捕获oOjbect。

我想知道,如果你们有任何处理这样的事情的经验,这会有多困难。 我也对其他可能的方法持开放态度,例如相反(在python脚本中运行C++对象(。谢谢!

解决方案 1创建一个小型 Python 脚本,用于调用函数并打印结果。 然后,在C++程序中使用popen调用python脚本并检索显示的值。

解决方案 2在 C++ 程序中嵌入 Python https://docs.python.org/2/extending/embedding.html

如果你只有很少的 Python 调用,我认为解决方案 1 是更快、更安全的方法。