網絡上查找到的幾乎都是 需要提前固定知道 接收字符(字節)數據的大小的方式,現在的數據大小方式 不需要提前知道如下
思路:
1 .C++,返回變長 指針或者字節 的地址給C# 接收,同時返回 該地址的數據長度給C#。
2 .C# 通過C++ 返回的數據長度,創建接收數據的byte[] 長度。
3.C# 通過返回的地址 拷貝讀取數據。
C++ 代碼如下:
extern "C" __declspec(dllexport) char * GetFileByteArray(wchar_t * BinfilePath, wchar_t *BinfileName,int indexFile, int * length) { char *chBinfilePath= nullptr, *chBinfileName = nullptr; wchar_tTranstoChar(BinfilePath, &chBinfilePath); wchar_tTranstoChar(BinfileName, &chBinfileName); char a[] = "13345zh中文 hello"; //前提條件需要 返回變長的指針 int fileCount = sizeof(a); char *att = new char[fileCount]; memcpy(att, a, fileCount); *length = fileCount-1; // C#獲得長度 free(chBinfilePath); free(chBinfileName); return att;// C# 獲得指針 }
C# 處理如下:
[DllImport("BASECORELIBRARY.dll", CharSet = CharSet.Unicode, CallingConvention = CallingConvention.StdCall)] public static extern IntPtr GetFileByteArray(string BinfilePath, string BinfileName, int indexFile,ref int length); int length = 0; IntPtr piBuf = InvokeDLL.GetFileByteArray(newFilePath, toBinName, 0, ref length); byte[] arrayBuf = new byte[length]; Marshal.Copy(piBuf,arrayBuf,0, length); string st= Encoding.Default.GetString(arrayBuf); Console.WriteLine(st);
輸出結果: 13345zh中文 hello