简体   繁体   English

将Python嵌入到C ++应用程序中

[英]Embedding Python into C++ application

Context: 语境:

An ongoing problem we have been facing is unit testing our market data applications. 我们一直面临的问题是对我们的市场数据应用进行单元测试。 These applications sit and observe data being retrieved from feeds and does something. 这些应用程序坐下来观察从源中检索的数据并执行某些操作。 Some critical events which are hard to trigger rarely occur and it is are difficult for the Testers to verify our applications perform correctly under all situations, hence we have to rely on unit tests. 一些难以触发的关键事件很少发生,并且测试人员很难在所有情况下验证我们的应用程序是否正确执行,因此我们必须依赖于单元测试。

These systems generally work by issuing callbacks (into our application) when an event has occurred, then our task to deal with this. 这些系统通常通过在事件发生时发出回调(进入我们的应用程序)来工作,然后我们的任务就是处理这个问题。

Solution I envision: 解决方案我设想:

Is it possible to embed Python, or extend (not 100% clear on this), so that a tester could fire up a Python REPL and issue function calls that are akin to callbacks which are then handled by our C++ classes. 是否可以嵌入Python或扩展(不是100%清楚),以便测试人员可以启动Python REPL并发出类似于回调的函数调用,然后由我们的C ++类处理。 Some form of dynamic manipulation of our objects at runtime. 在运行时对我们的对象进行某种形式的动态操作。

I do something similar to this in one of my projects by using SWIG to generate python bindings for the relevant parts of the C++ code. 我在我的一个项目中做了类似的事情,使用SWIG为C ++代码的相关部分生成python绑定。 Then I embed the interpreter as others have suggested. 然后我按照其他人的建议嵌入了翻译。 Having done that I can execute python code at will (eg PyRun_SimpleString ), which can access C++ code. 完成后我可以随意执行python代码(例如PyRun_SimpleString ),它可以访问C ++代码。 Normally I end up using something like a Singleton to make accessing specific C++ objects from python easier. 通常我最终使用类似Singleton的东西来更容易地从python访问特定的C ++对象。

Also worth a mention is directors in swig python modules, which allow virtual functions to be handled much more intuitively. 另外值得一提的是swig python模块中的导演 ,它允许更直观地处理虚拟功能。 Depending on quite what you're doing you might find these very helpful. 根据您正在做的事情,您可能会发现这些非常有帮助。

What you want to do is possible, though not trivial to get right. 你想做的事情是可能的,虽然不是很容易做对。 It sounds like you want to embed (rather than extend) Python. 听起来你想要嵌入(而不是扩展)Python。 Both topics are covered in the tutorial here . 这两个主题均包含在本教程这里

There's quite a lot of work in mapping from C++ classes to Python classes, and there are a number of things that can go wrong in subtle ways, particularly with memory leaks and multithreading (if your existing code is multi-threaded). 从C ++类到Python类的映射有很多工作,并且有许多方面可能会以微妙的方式出错,尤其是内存泄漏和多线程(如果您的现有代码是多线程的)。 However, if it's only for use in a testing situation and stability is not mission-critical then it might be less of a problem. 但是,如果它仅用于测试情况并且稳定性不是关键任务,那么它可能不是一个问题。

Yes, it is possible. 对的,这是可能的。 See this for the how. 请参阅此内容

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

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