C# 接收C++ dll 可变长字节或者 字符指针 char*

     网络上查找到的几乎都是 需要提前固定知道 接收字符(字节)数据的大小的方式,现在的数据大小方式 不需要提前知道如下

思路:

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            

 

posted @ 2019-12-21 17:40  孜然道  阅读(1200)  评论(0编辑  收藏  举报