简体   繁体   中英

Calling Python from .NET via C++ bridge

Once per a couple of months I google for "Call Python from .NET" when I am too tired to reinvent/port stuff and find some cool code in Python. The two popular solutions are to start an external process or to use IronPython

IronPython is not an option for me since the reason I might want to use Python is usually some libraries that depend on NumPy/ScyPy.

Recently I started to learn the very basics of C++ and have found that one could embed Python in C++, and have found an article with an example .

Calling C++ from .NET is very easy via P/Invoke. So my scenario is to call some Python script with data from .NET and get results back.

Before I start digging deeper I want to ask if someone has tried this approach, is this feasible or there are better ways?

Specifically,

  • Will all Python libs work when embedded, eg NumPy, ScyPy, Pandas, PyMC, etc.?
  • Will embedded Python work with C++/CLI in the same way as with standard C++?
  • How to pass complex data to Python: serialized to JSON or there is a mapping between types?

Performance is a concern: the main use case is to do some numeric work on a sliding window of real time data. I think external process is very slow for frequent calls - please correct me if I am wrong?

I have used it once in following way:-

There was a C# dll from which I need to query for data. So, I developed C++/CLI module to interact with that dll and handled some delegates and events corresponding to that data. Then C++ module would accept this data, process it and send it to python module.

Gap between python and c++ was filled using zmq ( replacement for plain sockets ) and google protocol buffers ( serialization and deserialization mechanism ). What python would do is just send request to C++ which then transfers that to C++/ CLI module which on getting data would push through zmq to python...

Consider spawning a python instance in a separate thread as a processing server - you can use messages to pass data to it and back from it, if your coupling is loose this could work much more nicely than external calls and would inherently mean that your numeric processing was on a separate core to your GUI. You also would skip the processing time inherent in loading new processes for each call.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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