python - 如何将 Python 嵌入到多平台 C++ 框架(JUCE)中?

标签 python c++ embed embedding python-embedding

我正在使用 JUCE 设计音乐训练游戏——一种多平台 C++ 框架,让我能够在接近线路的情况下编写音频/视频代码。

但是,我已经用 Python 编写了我的游戏玩法(控制流/数据处理)——它很复杂,我希望不断更改它,以便我可以尝试不同的游戏玩法。 Python 非常适合这种快速原型(prototype)制作工作。

所以我希望我的(平台无关,所以 Win/OSX/Lin/iOS/And)C++ 启动 Python 运行时,为它提供一个 .py 文件,然后调用该 .py 中的各种函数。此外,我希望能够从 .py 回调到 C++ 代码。

这里是相关的官方 Python 文档:https://docs.python.org/2/extending/extending.html

这是一篇 CodeProject 文章:http://www.codeproject.com/Articles/11805/Embedding-Python-in-C-C-Part-I

但是,它们似乎都没有解决多平台问题。

该技术似乎是与库 libpython.a 和#include 链接,其中包含用于启动运行时环境、加载脚本、执行 python 代码等的各种功能。

但是这个 libpython.a 肯定需要根据平台单独编译吗?如果是这样,这将不是一个非常干净的解决方案,那么我是否可以将 Python 源代码添加到我的项目中并让它编译 .a?

我该怎么做呢?

编辑:https://wiki.python.org/moin/boost.python/EmbeddingPython

EDIT2:我很确定在这里尝试引入完整的 CPython 源代码有点过分了——一定有人用 C/C++ 做了一些精简的 Python 实现,它不支持任何系统调用/多线程/花哨的-stuff——只是通过 Python 语法逐行工作。翻看https://wiki.python.org/moin/PythonImplementations但我看不到明显的候选人。

编辑 3:https://github.com/micropython/micropython应该添加到最后一页,但看起来仍然不是我想要的

最佳答案

有一个 entire chapter of the Python docs解释了将 Python 解释器嵌入到另一个应用程序中可以采用的不同方法。

Embedding Python is similar to extending it, but not quite. The difference is that when you extend Python, the main program of the application is still the Python interpreter, while if you embed Python, the main program may have nothing to do with Python — instead, some parts of the application occasionally call the Python interpreter to run some Python code.

So if you are embedding Python, you are providing your own main program. One of the things this main program has to do is initialize the Python interpreter. At the very least, you have to call the function Py_Initialize(). There are optional calls to pass command line arguments to Python. Then later you can call the interpreter from any part of the application.

There are several different ways to call the interpreter: you can pass a string containing Python statements to PyRun_SimpleString(), or you can pass a stdio file pointer and a file name (for identification in error messages only) to PyRun_SimpleFile(). You can also call the lower-level operations described in the previous chapters to construct and use Python objects.

A simple demo of embedding Python can be found in the directory Demo/embed/ of the source distribution.

关于python - 如何将 Python 嵌入到多平台 C++ 框架(JUCE)中?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25568417/

相关文章:

jquery - 嵌入式 Youtube 视频的缩略图模糊

python - Linux 桌面文件 Exec 不使用用户 session

python - 如何将 NLTK 索引结果保存在列表中?

c++ - 这是在 C++ 中将一个类对象包含在另一个类中的最佳方式

c++ - 只有静态方法的类比命名空间更可取吗?

javascript - 如何使用(.xlsx 或 .pdf)网址在 react/javascript 中显示(只读)xlsx、pdf 文件?

python - 这是 linux 还是 virtualenv 错误?

python - 将 numpy boolean 选择器限制为前几个真值的有效方法

c++ - Boost 程序参数可以解析一个 wstring,但强制它变成一个字符串?

html - 嵌入可以由查看者排序的谷歌表格单元格