- .NET Core 2.0 By Example
- Rishabh Verma Neha Shrivastava
- 121字
- 2021-06-24 18:31:03
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.