From: David P. <dpi...@me...> - 2007-09-11 00:53:56
|
I've noticed that strings are returned from C++ using the following C# helper methods (two different methods for the two character sizes): // Helper for wide strings defined in wchar.i. // This is converted to a delegate and marshaled to a function pointer // that is stored in the C global variable SWIG_csharp_wstring_callback. static string CreateWString([MarshalAs(UnmanagedType.LPWStr)]IntPtr cString) { return System.Runtime.InteropServices.Marshal.PtrToStringUni(cString); } // Helper for ASCII strings defined in csharphead.swg // This is converted to a delegate and marshaled to a function pointer // that is stored in the C global variable SWIG_csharp_string_callback. static string CreateString(string cString) { return cString; } My question is, how does this "reverse marshalling" work when managed code is called from unmanaged code? I have not found anything on the subject at MSDN. I'm puzzled as to how System.String can be returned to unmanaged code without leaking memory and without any risk of premature garbage collection, because immediately after CreateString() returns, a managed reference to the returned System.String no longer exists. Another odd thing is that the two callbacks have different return types on the C side, even though, in both cases, the return type is "string" on the C# side: typedef char * (SWIGSTDCALL* SWIG_CSharpStringHelperCallback)(const char *); public delegate string SWIGWStringDelegate(IntPtr message); typedef void * (SWIGSTDCALL* SWIG_CSharpWStringHelperCallback)(const wchar_t *); How could CreateString return char* when strings are composed of wide characters? Has anyone seen documentation about reverse marshalling? I can't find any. |