Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Incorrect marshalling of string in Py_SetPythonHome #179

Closed
leomeuk opened this issue Mar 8, 2016 · 3 comments · Fixed by #415
Closed

Incorrect marshalling of string in Py_SetPythonHome #179

leomeuk opened this issue Mar 8, 2016 · 3 comments · Fixed by #415

Comments

@leomeuk
Copy link

leomeuk commented Mar 8, 2016

I noticed that when PythonEngine.PythonHome was set and a subsequent Initialize() call was made my .Net application would close unexpectedly.

It looks like the call to Py_SetPythonHome made in runtime.cs is implicitly marshalling the string to a char array for the unmanaged code. My suspicion is that the Python sourcecode is keeping a record of the pointer rather than making a copy of the data. The managed runtime will free the memory allocated to char array as soon as the function finishes executing leaving a dangling pointer. This then leads to the unexpected Initialize() behaviour.

[DllImport(Runtime.dll, CallingConvention = CallingConvention.Cdecl,
    ExactSpelling = true, CharSet = CharSet.Ansi)]
internal unsafe static extern void
Py_SetPythonHome(string home);

The solution appears to be to explicitly marshal the string and hang onto the pointer until it is no longer needed, i.e.

[DllImport(Runtime.dll, CallingConvention = CallingConvention.Cdecl,
     ExactSpelling = true, CharSet = CharSet.Ansi)]
internal unsafe static extern void
Py_SetPythonHome(IntPtr home);
IntPtr str = Marshal.StringToHGlobalAnsi(@"C:\Python27");
Py_SetPythonHome(str);
// do stuff
Marshal.FreeHGlobal(str);

Running Win7, .Net4.5 and Python 2.7.11.

@den-run-ai
Copy link
Contributor

@leomeuk looks like you are correct - I tested this crash in csi:

Microsoft (R) Roslyn C# Compiler version 1.1.0.51204
Loading context from 'CSharpInteractive.rsp'.
Type "#help" for more information.
> #r "C:\Python\Python27\Lib\site-packages\Python.Runtime.dll"
> using Python.Runtime;
> PythonEngine.PythonHome = @"C:\Python\Python27";
> PythonEngine.Initialize();
> PythonEngine.PythonHome
Hosting process exited with exit code -1073740940.
Loading context from 'CSharpInteractive.rsp'.

@den-run-ai
Copy link
Contributor

@leomeuk can you submit a patch and corresponding unit test?

@leomeuk
Copy link
Author

leomeuk commented Mar 12, 2016

@denfromufa I'll look at doing so this weekend.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

Successfully merging a pull request may close this issue.

2 participants