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
500 views
in Technique[技术] by (71.8m points)

c# - Multiple python interpreters in one process with PythonNet?

I'm trying to host multiple python runtimes in a C# process through PythonNet.

At the moment, I'm running into issues with this approach, and I'm trying to figure out if it's an issue on my end, of whether it's just generally impossible to host multiple interpreters in one process. I've found conflicting information on the latter, however some devs seemed to suggest this "should" be possible.

My approach is effectively the following:

  1. For each interpreter, I first load PythonNet's PythonRuntime.dll into a dedicated AssemblyLoadContext
  2. From that loaded assembly, through reflection, I invoke PythonEngine.PythonHome = (path to a conda environment)
  3. This triggers a load attempt of python39.dll, which I also resolve through my custom assembly loader - to be on the safe side, I copy python39.dll into a temporary file with random name, and load that. (i.e.: for each interpreter I spawn, I actually load an individual copy of python39.dll into the process)
  4. I now acquire Py.GIL() and try to load a module through Py.Import("sys") - both of that, again through reflection on the type of the individually loaded PythonRuntime.dll

Works fine if I only spawn one of those interpreters. However, when I do this for a bunch concurrently, importing the "sys" module causes a System.AccessViolationException - Attempted to read of write protected memory, caused by PyImport_ImportModule.

Am I doing something wrong here? Can this even be done, or does CPython actually not support this?


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

1 Reply

0 votes
by (71.8m points)
等待大神答复

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

Just Browsing Browsing

[2] html - How to create even cell spacing within a

1.4m articles

1.4m replys

5 comments

57.0k users

...