Sign in to follow this  
Niksan2

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

Recommended Posts

Niksan2    265
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

Share this post


Link to post
Share on other sites
Cygon    1219
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-

Share this post


Link to post
Share on other sites
Niksan2    265
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.

Share this post


Link to post
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now

Sign in to follow this