- .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.
推薦閱讀
- 企業(yè)性能測試:體系構(gòu)建、落地指導(dǎo)與案例解讀
- 中文版Revit 2018基礎(chǔ)培訓(xùn)教程(全彩版)
- 從缺陷中學(xué)習(xí)C/C++
- 百度SEO一本通
- 開發(fā)者關(guān)系:方法與實踐
- 卡爾曼濾波原理及應(yīng)用:MATLAB仿真(第2版)
- 軟件質(zhì)量管理指南
- 從隱秩序到顯規(guī)則:工程體系基于V++規(guī)則引擎的生態(tài)演進(jìn)
- 負(fù)載均衡:高并發(fā)網(wǎng)關(guān)設(shè)計原理與實踐
- 軟件開發(fā)大講堂·從入門到精通-第一輯(套裝共5冊)
- 軟件工程:理論與實踐(第2版)
- 移山之道:VSTS軟件開發(fā)指南
- 分布式高可用算法
- IEC算法及其在多目標(biāo)優(yōu)化中的應(yīng)用
- Arduino與LabVIEW開發(fā)實戰(zhàn)