如何在使用嵌入式 Python 执行期间解析绑定?
我正在将 Python 嵌入到 C++ 应用程序中。我计划使用 PyEval_EvalCode
执行 Python 代码,但我不是提供 locals 和 globals 作为字典,而是寻找一种方法让我的程序动态解析符号引用。
例如,假设我的 Python 代码由以下表达式组成:
bear + lion * bunny
而不是将 bear
、lion
和 bunny
及其关联对象放入字典中当我传递给 PyEval_EvalCode
时,我希望 Python 解释器回调我的程序并请求这些命名对象。
有办法做到这一点吗?
I'm embedding Python into a C++ application. I plan to use PyEval_EvalCode
to execute Python code, but instead of providing the locals and globals as dictionaries, I'm looking for a way to have my program resolve symbol references dynamically.
For example, let's say my Python code consists of the following expression:
bear + lion * bunny
Instead of placing bear
, lion
and bunny
and their associated objects into the dictionaries that I'm passing to PyEval_EvalCode
, I'd like the Python interpreter to call back my program and request these named objects.
Is there a way to accomplish this?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
通过提供本地和全局字典,您可以提供执行评估代码的环境。这有效地为您提供了一个将名称映射到 C++ 应用程序中定义的对象的接口。
你能解释一下为什么你不想使用词典吗?
您可以做的另一件事是在 C++ 中处理字符串并在评估代码之前进行字符串替换......
By providing the locals and globals dictionaries, you are providing the environment in which the evaled code is executed. That effectively provides you with an interface to map names to objects defined in the C++ app.
Can you clarify why you do not want to use the dictionaries?
Another thing you could do is process the string in C++ and do string substitution before you eval the code....
可能吧。我从来没有尝试过这个,但理论上你可能能够在 C++ 中实现一个小的扩展类,它重写 __getattr__ 方法(可能通过 tp_as_mapping 或 tp_getattro PyTypeObject 的函数指针)。将其实例作为本地变量和/或全局变量传递给
PyEval_EvalCode
并且应要求您的 C++ 方法解析您的狮子、老虎和狮子。为你熊。Possibly. I've never tried this but in theory you might be able to implement a small extension class in C++ that overrides the
__getattr__
method (probably via thetp_as_mapping
ortp_getattro
function pointers ofPyTypeObject
). Pass an instance of this as locals and/or globals toPyEval_EvalCode
and your C++ method should be asked to resolve your lions, tigers, & bears for you.