How to indicate whether to take responsibility for a gated string or not?

Suppose I have x.dll in C ++ that looks like this:

MYDLLEXPORT const char* f1() { return "Hello"; } MYDLLEXPORT const char* f2() { char* p = new char[20]; strcpy(p, "Hello"); return p; } 

Now suppose I want to use this in C #

 [DllImport("x.dll")] public static extern string f1(); [DllImport("x.dll")] public static extern string f2(); 

Is there a way to tell the CLR to take ownership of the string returned from f2 but not f1? The fact is that the fact that the line returned from f1 will eventually be freed, deleted, or something else GC will be equally bad that the line returned from f2 will not. Hope the question was clear. thanks in advance

+7
source share
1 answer

If you have any influence on the implementation of the DLL, I strongly recommend that you simply not do this, as you showed in your example. Otherwise, please clarify the issue to mention this limitation.

If you need to return the selected heap line from the dll, you should also provide a cleanup function (it is always good practice to export dynamically allocated memory from the dll). You P / Call the highlighting function with IntPtr return and marshal that with one of Marshal.PtrToString... at http://msdn.microsoft.com/en-us/library/atxe881w.aspx and end up calling the cleanup function for your own part of things.

Another way is to use BSTR (example from Marshaling BSTRs in COM / Interop or P / Invoke ):

Native:

 __declspec(dllexport) void bstrtest(BSTR *x) { *x = SysAllocString(L"Something"); } 

Managed:

 [DllImport("mydll.dll")] extern static void bstrtest(ref IntPtr dummy); static void Main(string[] args) { var bstr = IntPtr.Zero; bstrtest(ref bstr); var text = Marshal.PtrToStringBSTR(bstr); Console.WriteLine(text); Marshal.FreeBSTR(bstr); } 

I just found a similar question about SO: PInvoke for a C function that returns char *

+4
source

All Articles