c++ - 将 C++ 字符串传递给 Python

标签 c++ python

如何将字符串从 C++ 传递到我的 Python 函数?我想在我的 C++ 应用程序中获取字符串并在 Python 中解析它

最佳答案

首先初始化所有需要的变量。

Py_Initialize();
object  main_module = import("__main__");//boost::python objects
object  dictionary = main_module.attr("__dict__");

运行一段代码来创建一个变量并设置一个初始值并在 python 中打印它。

boost::python::exec("resultStr = 'oldvalue'", dictionary);
PyRun_SimpleString("print resultStr");//new value will reflect in python

从 C++ 中读取相同的变量。

boost::python::object resultStr = dictionary["resultStr"];//read value from python to c++
std::string &processedScript = extract<std::string>(resultStr);

上面的字典对象就像一个共享 map 。你可以从 C++ 中设置一个变量。 然后从 python 检查新值。

dictionary["resultStr"] = "new value";//set the variable value
PyRun_SimpleString("print resultStr");//new value will reflect in python

享受编码乐趣。 谢谢。

关于c++ - 将 C++ 字符串传递给 Python,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7081472/

相关文章:

c++ - 交换重载算术运算符的参数

python - 设置 python emacs 环境 mac os x

python - 如何将 Excel PivotCache 提取到 Pandas Data Frame 中?

c++ - typename 定义 map 数据时的类型名称, map 数据是带有少量模板的函数指针

c++ - 在 C++ 中标记字符串并包含分隔符

c++ - 如何使用 std::bind 和 lambda

python - 如何从 python 调用用 C 编写的 GObject 类上的方法?

python - 在 Python 中对整个应用程序进行回归测试

python - 在 Scrapy 中使用项目

c++ - dlsym() 解决方法返回类型