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

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.

主站蜘蛛池模板: 富蕴县| 腾冲县| 龙江县| 石台县| 儋州市| 宝应县| 县级市| 桐庐县| 濮阳县| 兰州市| 阿拉善左旗| 山西省| 泰来县| 泗阳县| 泉州市| 汝阳县| 广德县| 古交市| 叙永县| 萨迦县| 佛山市| 徐水县| 彭山县| 固镇县| 武清区| 曲水县| 江油市| 尚志市| 类乌齐县| 安陆市| 抚顺县| 天柱县| 海宁市| 林芝县| 淮安市| 新和县| 托里县| 穆棱市| 南汇区| 乐至县| 腾冲县|