官术网_书友最值得收藏!

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.

主站蜘蛛池模板: 洮南市| 新民市| 游戏| 镇安县| 石柱| 南澳县| 长子县| 灵宝市| 龙南县| 东丰县| 新营市| 新昌县| 台中县| 横峰县| 霍城县| 山东省| 蒙山县| 平定县| 双辽市| 广宗县| 静海县| 郑州市| 龙口市| 永川市| 乌审旗| 浮山县| 阿荣旗| 额济纳旗| 屏边| 自治县| 潼关县| 岳阳县| 北票市| 洛扎县| 大化| 晋州市| 瓦房店市| 枝江市| 蓝田县| 同江市| 民和|