[.net] char* return from interop and marshal as string

Started by
1 comment, last by Niksan2 16 years, 11 months ago
Hi, I'm working with some dll's I've been supplied with and one of the functions returns a char* which in the managed side marshal the return value as a string, however it seems that the managed side tries to delete the pointer that's returned and yields in a "HEAP[SumoTool.exe]: Invalid Address specified to RtlFreeHeap( 00140000, 080608D0 )" each time the function is called. I read on some sites that you should have a wrapper, with the interop returning a IntPtr and then doing a Marshal.PtrToStringAnsi() but in doing this I still get Heap message, is there anyway to get the char* as a string and have it not attempt to free the pointer ? Cheers
Advertisement
Blame the writer of that DLL for its weak design! It is not possible to see, without referring to the documentation, whether you're supposed to free the memory or not. If it indeed needs to be freed, the library would only work on platforms supporting a shared memory allocator (eg. in the MT DLL runtime setting for VC++ users). If it's the other way around and it mustn't be freed, the library either is not thread safe or has a memory leak :)

I'm pretty sure Marshal.PtrToStringAnsi() does not free the memory. It isn't even able to, since it has no connection to the C runtime you're using (which manages the memory allocated on the heap and is responsible for the assertion message). The runtime can really be anything from VC 6.0, 7.0, 7.1 or 8.0 to CygWin32 or a custom one the .NET BCL can impossibly have knowledge of.

If you're writing this in C#, try declaring the function as returning a plain int and just call the function as if it had no return value. I bet the Heap Assertion will still be triggered and it comes down to an implementation error in the DLL you're using. Or maybe you just forgot to call some initialization function in the DLL or something.

-Markus-
Professional C++ and .NET developer trying to break into indie game development.
Follow my progress: http://blog.nuclex-games.com/ or Twitter - Topics: Ogre3D, Blender, game architecture tips & code snippets.
Nevermind I was being a numpty, for a change :) I wasn't actually using the new c# interop code, so the IntPtr stuff does actually work, my bad, gave you points anyway.. I think I'm getting too old for this stuff.

This topic is closed to new replies.

Advertisement