Tuesday, July 09, 2013

How do we send a string to the native world and how do we receive a string back

More often than not we have scenarios where our application would be based on .net, we would have to communicate with a native dll and you do not have the source code for the native dll  . I have described one such scenario here. When working with one of our customers where they were trying to return a string from the native world their application was crashing . I wrote the sample below and some tools aided me during the process and hence I am sharing my experience . Although the dll or the exe's functionality works splendidly , we end up crashing the application in such issues. It's mostly because returning a System.String type from a PInvoke function requires great care. The CLR must transfer the memory from the native representation into the managed one .

The problem though comes with what to do with the native memory that was returned from the native function. The CLR assumes that,

a.The native memory needs to be freed .

b.The native memory was allocated with CoTaskMemAlloc

Therefore it will marshal the string and then call CoTaskMemFree on the native memory blob. Unless you actually allocated this memory with CoTaskMemAlloc this will at best cause a crash in the application.

We had the signature of the function in the native dll which is similar to char *TESTIN(char in[]) . Based on my previous experiences I was able to write the signature to import this function in the c# application . How ever a handy tool here would be to try pinvoke interop assistant . You can generate the signature in both vb.net as well as c# .

There are many other cool features which you can explore .

QR: Inline image 1