C # C ++ dll receiving variable length byte or character char * pointer

     Found almost always fixed in advance to know the size of the received character (byte) of data on the network, are now the size of the data does not need know the following manner

Ideas:

1 .C ++, return variable length byte pointer or address to the reception C #, and returns the address to the data length of C #.

 2 .C # C ++ returned by the length of the data, receiving data created byte [] length.

 3.C # copy by returning the address of the read data.

 

 

C ++ code as follows: 

 

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 new  char [fileCount]; 
     the memcpy (ATT, A, fileCount);

      * = fileCount-length. 1; // C # length obtained 

     Free (chBinfilePath);
      Free (chBinfileName); 
    
     return   ATT; // C # pointer obtained 
    
 }

 

C # processing is as follows: 

        [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);

 

Output:  13345zh Chinese hello            

 

Guess you like

Origin www.cnblogs.com/bkyrslf/p/12077637.html