diff --git a/src/Python.Runtime/pythonengine.cs b/src/Python.Runtime/pythonengine.cs index 78d3be87a..cc552ad2d 100644 --- a/src/Python.Runtime/pythonengine.cs +++ b/src/Python.Runtime/pythonengine.cs @@ -148,7 +148,7 @@ public static void Initialize() IntPtr builtins = Runtime.PyEval_GetBuiltins(); Runtime.PyDict_SetItemString(module_globals, "__builtins__", builtins); - var assembly = Assembly.GetEntryAssembly(); + var assembly = typeof(Runtime).GetTypeInfo().Assembly; using (Stream stream = assembly.GetManifestResourceStream("Python.Runtime.resources.clr.py")) using (StreamReader reader = new StreamReader(stream)) { @@ -257,6 +257,7 @@ public static void Shutdown() { if (initialized) { + Runtime.Py_Main(3, new[] { "some.exe", "-c", "exit" }); Runtime.Shutdown(); initialized = false; } diff --git a/src/Python.Runtime/runtime.cs b/src/Python.Runtime/runtime.cs index 2557d1d93..cdc37461d 100644 --- a/src/Python.Runtime/runtime.cs +++ b/src/Python.Runtime/runtime.cs @@ -2,6 +2,7 @@ using System.Runtime.InteropServices; using System.Security; using ReflectionBridge.Extensions; +using System.Linq; #if (UCS4) using System.Text; @@ -703,10 +704,38 @@ internal unsafe static extern IntPtr PyGILState_GetThisThreadState(); #if (PYTHON32 || PYTHON33 || PYTHON34 || PYTHON35) - [DllImport(Runtime.dll, CallingConvention=CallingConvention.Cdecl, - ExactSpelling=true, CharSet=CharSet.Ansi)] - public unsafe static extern int - Py_Main(int argc, [MarshalAsAttribute(UnmanagedType.LPArray, ArraySubType=UnmanagedType.LPWStr)] string[] argv); + [DllImport(Runtime.dll, CallingConvention = CallingConvention.Cdecl, + ExactSpelling = true, CharSet = CharSet.Ansi)] + private unsafe static extern int Py_Main(int argc, [MarshalAsAttribute(UnmanagedType.SysUInt)] IntPtr lplpargv); + + public unsafe static int Py_Main(int argc, string[] argv) + { + // Totally ignoring argc. + argc = argv.Length; + + int allStringsLength = argv.Sum(x => x.Length + 1); + int requiredSize = IntPtr.Size * argc + allStringsLength * UCS; + IntPtr mem = Marshal.AllocHGlobal(requiredSize); + try + { + // Preparing array of pointers to UTF32 strings. + IntPtr curStrPtr = mem + argc * IntPtr.Size; + for (int i = 0; i < argv.Length; i++) + { + Encoding enc = UCS == 2 ? Encoding.Unicode : Encoding.UTF32; + byte[] zstr = enc.GetBytes(argv[i] + "\0"); + Marshal.Copy(zstr, 0, curStrPtr, zstr.Length); + Marshal.WriteIntPtr(mem + IntPtr.Size * i, curStrPtr); + curStrPtr += zstr.Length; + } + return Py_Main(argc, mem); + } + finally + { + Marshal.FreeHGlobal(mem); + } + } + #else [DllImport(Runtime.dll, CallingConvention = CallingConvention.Cdecl, ExactSpelling = true, CharSet = CharSet.Ansi)]