垂直行業(yè)門戶網(wǎng)站建設(shè)方案百度權(quán)重怎么提高
一.背景
???在 C# 中沒有 char* 類型,因為 C# 是一種托管語言,它的設(shè)計目標(biāo)是提供更高級別的安全性和內(nèi)存管理,避免使用像 C 或 C++ 中的指針操作,以防止常見的指針相關(guān)錯誤,如內(nèi)存泄漏和懸空指針。
二.c#調(diào)用c++的dll,char*參數(shù)問題解決的三種方法
dll API原型:DLLEPXORT int EXCALL Net_connect(char* IP);
1.方法一:用string代替char *
(1)示例代碼:
聲明:
?[DllImport("ST_DLL.dll")]
?extern static int Net_connect(string IP);
調(diào)用:
?string ipAddress = "192.168.1.10";
?int ret = Net_connect(ipAddress);
2.方式二:用byte[]代替char *
(1)示例代碼:
聲明:
?[DllImport("ST_DLL.dll")]
?extern static int Net_connect(byte[] IP);
調(diào)用:
?string ipAddress = "192.168.1.10";
?byte[] data = Encoding.Default.GetBytes(ipAddress);
?int ret = Net_connect(data);
?2.方式三:用IntPtr代替char *
?當(dāng)與外部非托管代碼(如 C 或 C++ 的 DLL)交互時,也可以使用 IntPtr 和 Marshal 類來處理指針。
(1)示例代碼:
聲明:
?[DllImport("ST_DLL.dll")]
?extern static int Net_connect(IntPtr IP);
調(diào)用:
?string ipAddress = "192.168.1.10";
?IntPtr strPtr = Marshal.StringToHGlobalAnsi(ipAddress);
?int ret = Net_connect(strPtr);