Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
226 views
in Technique[技术] by (71.8m points)

c# - Call Python from .NET

I have some code written in Python which can not be transferred to a .NET language. I need to call one of these functions from my .NET WinForms application.

Now, I do it by starting the Python script as a separate process and pass parameters to it as command line arguments. It works, but I don't really like this solution. I'd like to improve it to a better one.

Is there any better way to call a function of a .py script from a .NET application? What is the best way to do it?

Note: IronPython is NOT an option for this Python script

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

This might be a lot more work than launching the Python process, but here's an alternate solution.

You can embed Python into another program. The API is for C and Interop from .NET will probably be a major pain. If you're into a bit of a safer way to handle the native Python API, you can look into Boost.Python, which, among its less advertised features, has support for embedding.

With these tools, you can write a C++ managed DLL that uses Boost.Python to load the Python interpreter and execute any Python script. Thus, you can execute any Python code directly in the hosting process, eliminating the use of an external process and any form of IPC.

Edit: AFAIK, all you have to add to your installation procedure is the deployment of the Python DLL and Boost.Python DLL.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...