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:
- For each interpreter, I first load PythonNet's PythonRuntime.dll into a dedicated AssemblyLoadContext
- From that loaded assembly, through reflection, I invoke PythonEngine.PythonHome = (path to a conda environment)
- 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)
- 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?
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…