When not to use P/Invoke

Utilizing P/Invoke isn't fitting for all C-style methods in DLLs. Let's take an example where we create a string in a C++ program and display it in a C# application:

#include "stdafx.h"const char * HelloMsg(){  char * msg = "Hello .NET Core.";  return msg;}int main(){  printf(HelloMsg());}

Now, using P/Invoke, pass the library in the DllImport attribute:

[DllImport("HelloMsgLib.so")]public static extern char *  HelloMsg();

The trouble here is that we can't erase the memory for the unmanaged string returned by msg. Different methods called through P/Invoke restore a pointer and do not need to be deallocated by the client. For this situation, utilizing the marsheling is a more suitable approach.

Get .NET Core 2.0 By Example now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.