简体   繁体   English

将 Python 源代码嵌入 C++ 作为字符串

[英]Embed Python source code in C++ as string

I'm writing a C++ program that requires Python (3.11) code to be embedded into it and am using Python.h to try and accomplish this.我正在编写一个 C++ 程序,需要将 Python (3.11) 代码嵌入其中,并使用 Python.h 来尝试完成此操作。 The general idea is that my a python script, which will be stored by the C++ program as a string, as I'll be performing operations on the source at runtime, will contain a "main()" function which returns an array of known size.一般的想法是我的 python 脚本将由 C++ 程序存储为字符串,因为我将在运行时对源执行操作,它将包含一个“main()”function,它返回一个已知数组尺寸。

I'm aware I can do it via:我知道我可以通过以下方式做到这一点:

...
PyObject *pName = PyString_FromString("main");
PyObject *pModule = PyImport_Import(pName)
...

However, in order to actually execute the script, I would need to write it to a file just so that python could read it again.但是,为了实际执行脚本,我需要将它写入一个文件,以便 python 可以再次读取它。 This adds extra time to execution that I'd prefer to avoid.这会增加我希望避免的额外执行时间。 Isn't there some way in which I can pass python the source code directly as a string and work from there?有没有什么方法可以直接将 python 源代码作为字符串传递并从那里开始工作? Or am I just screwed?还是我只是搞砸了?

EDIT: BTW, PyRun_SimpleString does not do what I want, as it doesn't return anything from the executed code.编辑:顺便说一句,PyRun_SimpleString 没有执行我想要的操作,因为它不会从执行的代码中返回任何内容。

Found the answer thanks to nick in the comments.感谢尼克在评论中找到答案。 An example of usage of PyRun_String: https://schneide.blog/2011/10/10/embedding-python-into-cpp/ , and extracting list variables from python script https://docs.python.org/3/c-api/list.html The final frankenstein: PyRun_String 的用法示例: https://schneide.blog/2011/10/10/embedding-python-into-cpp/ ,并从 python 脚本中提取列表变量https://docs.python.org/3/c -api/list.html最后的科学怪人:

PyObject *main = PyImport_AddModule("__main__");
PyObject *globalDictionary = PyModule_GetDict(main);
PyObject *localDictionary = PyDict_New();
PyRun_String("a=[0, 1, 2, 3, 4, 5]", Py_file_input, globalDictionary, localDictionary);
    
PyObject *result = PyDict_GetItemString(localDictionary, "a");

double a[6];
for (int i = 0; i < PyList_Size(result); i++) {
    a[i] = PyFloat_AsDouble(PyList_GetItem(result, i));
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM