博客园  :: 首页  :: 联系 :: 管理

C#和C++的二进制通讯

Posted on 2008-07-16 11:16  sunrack  阅读(1116)  评论(1编辑  收藏  举报
一、C++

class BusinessData
{
public:
    
int x;
    
int test[3];
    
double y;
    
char str[3];
    
char t;
    char strName[5];
};

int _tmain(int argc, _TCHAR* argv[])
{
    BusinessData curBusinessData;

    curBusinessData.x 
= 5;
    curBusinessData.y 
= 7.123468;
    curBusinessData.t 
= 'T';


    
for(int i= 0; i<3; i++)
    {
        curBusinessData.test[i] 
= i+1;
    }

    curBusinessData.str[
0= 'a';
    curBusinessData.str[
1= 'b';
    curBusinessData.str[
2= '\0';

    strcpy(curBusinessData.strName,"测试");

    ofstream fout(
"C:\\file.dat", ios::binary);
    fout.write((
char *)(&curBusinessData), sizeof(curBusinessData));
    fout.close();

    
return 0;
}


二、C#

   [StructLayoutAttribute(LayoutKind.Sequential, CharSet = CharSet.Ansi, Pack = 0)]
    
public class BusinessData
    {
        
//[FieldOffset(0)]
        
//[MarshalAs(UnmanagedType.I4)]
        public int x;


        [MarshalAs(UnmanagedType.ByValArray, SizeConst 
= 3)]
        
public int[] test;

        
//[FieldOffset(8)]
        
//[MarshalAs(UnmanagedType.R8)] 
        public double y;

        [MarshalAs(UnmanagedType.ByValTStr, SizeConst 
= 3)]
        
public string str;

        
//[FieldOffset(2)]
        public char t;

        [MarshalAs(UnmanagedType.ByValTStr, SizeConst = 5)]
        public string strName;

    };


 /**//// <summary>
        
/// 结构体转byte数组
        
/// </summary>
        
/// <param name="structObj">要转换的结构体</param>
        
/// <returns>转换后的byte数组</returns>
        public static byte[] StructToBytes(object structObj)
        {
            
//得到结构体的大小
            int size = Marshal.SizeOf(structObj);
            
//创建byte数组
            byte[] bytes = new byte[size];
            
//分配结构体大小的内存空间
             IntPtr structPtr = Marshal.AllocHGlobal(size);
            
//将结构体拷到分配好的内存空间
             Marshal.StructureToPtr(structObj, structPtr, false);
            
//从内存空间拷到byte数组
             Marshal.Copy(structPtr, bytes, 0, size);
            
//释放内存空间
             Marshal.FreeHGlobal(structPtr);
            
//返回byte数组
            return bytes;
         }

     
/**//// <summary>
        
/// byte数组转结构体
        
/// </summary>
        
/// <param name="bytes">byte数组</param>
        
/// <param name="type">结构体类型</param>
        
/// <returns>转换后的结构体</returns>
        public static object BytesToStuct(byte[] bytes,Type type)
        {
            
//得到结构体的大小
            int size = Marshal.SizeOf(type);
            
//byte数组长度小于结构体的大小
            if (size > bytes.Length)
            {
                
//返回空
                return null;
             }
            
//分配结构体大小的内存空间
             IntPtr structPtr = Marshal.AllocHGlobal(size);
            
//将byte数组拷到分配好的内存空间
             Marshal.Copy(bytes,0,structPtr,size);
            
//将内存空间转换为目标结构体
            object obj = Marshal.PtrToStructure(structPtr, type);
            
//释放内存空间
             Marshal.FreeHGlobal(structPtr);
            
//返回结构体
            return obj;
         }



       static void Main(string[] args)
        {
           
int rawsize = Marshal.SizeOf(typeof (BusinessData));

            
byte[] buffer = new byte[rawsize];

            FileStream curSream 
= new FileStream("C:\\file.dat", FileMode.Open);

            BinaryReader curReader 
= new BinaryReader(curSream);

            curReader.Read(buffer, 
0, rawsize);

            
object obj = BytesToStuct(buffer, typeof(BusinessData));

            BusinessData curBusinessData 
= (BusinessData)obj;

            
if (curBusinessData != null)
            {

            }
        }