- .NET Core 2.0 By Example
- Rishabh Verma Neha Shrivastava
- 121字
- 2021-06-24 18:31:02
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.
推薦閱讀
- Spring源碼深度解析
- 軟件工程基礎(chǔ)教程
- Revit 2020中文版從入門到精通
- CAE分析大系:ANSYS?Workbench結(jié)構(gòu)分析與實(shí)例詳解
- VMware vSphere 7.0云平臺(tái)運(yùn)維與管理(第2版)
- 程序員的制勝技
- Python與數(shù)據(jù)挖掘
- AIDevOps:智能微服務(wù)開發(fā)、運(yùn)維原理與實(shí)踐
- 卡爾曼濾波原理及應(yīng)用:MATLAB仿真(第2版)
- 3D打印創(chuàng)意小創(chuàng)客
- 自己動(dòng)手構(gòu)造編譯系統(tǒng):編譯、匯編與鏈接
- Python跨平臺(tái)應(yīng)用軟件開發(fā)實(shí)戰(zhàn)
- 嵌入式軟件測(cè)試:方法、案例與模板詳解
- 現(xiàn)代軟件工程
- 軟件測(cè)試項(xiàng)目實(shí)戰(zhàn)