将c++字符串传递给Python
passing C++ string to 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);
上面的字典对象类似于一个共享映射。您可以从c++中设置变量。然后检查python的新值。
dictionary["resultStr"] = "new value";//set the variable value
PyRun_SimpleString("print resultStr");//new value will reflect in python
玩得开心。谢谢。
相关文章:
- 如何运行位于boost/libs/python/example/tutorial目录中的hello.cpp和Jamfil
- Pybind11:将元组列表从Python传递到C++
- 如何在c++中使用引用实现类似python的行为
- 是否可以通过C++扩展强制多个python进程共享同一内存
- 递归列出所有目录中的C++与Python与Ruby的性能
- IPC使用多个管道和分支进程来运行Python程序
- 从python中调用C++函数并获取返回值
- Python 3.7 和 excess_args 的 SWIG 问题
- Python中的for循环与C++有何不同
- 使用Pybind11向Python公开Eigen::张量
- Python str to C++ to Python str
- 如何使用Python从C++中读取谷物序列化数据
- 如何在C++中使用pybind11加载一个pickle python列表
- 如何在c++中使用system()来运行包含空格的python脚本
- python集合的C++等价物是什么.计数器
- 如果C++对象的类在另一个boost模块中声明,如何使用boost将指向该对象的指针返回到python
- 从python调用openMP共享库时,未定义opnMP函数
- 使用JsonCpp将数据返回到带有pybind11的python会在python调用中产生Symbol not foun
- 如何将真正的字符串从python c-api转换为python脚本
- Python ctype 'c_char_p' Memory Leak