用C#读取C/C++中struct数据类型生成的文件

本文介绍如何使用C++创建结构体并将其写入文件,然后在C#中读取该文件,并将数据转换为相应的结构体。涉及到C++的文件I/O操作、C#中的文件流及内存操作。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

C++中的struct写成文件:

#include "stdafx.h"

struct TestStruct    

{           

    
float f1;           

    
float f2;       

    
short s1;           

    
short s2;           

    
float arrf[8];      

}
;

 

int _tmain(int argc, _TCHAR* argv[])

{

    FILE 
*stream;

    TestStruct teststruct;

 

    teststruct.f1
=1.0;

    teststruct.f2
=2.0;

    teststruct.s1
=3;

    teststruct.s2
=4;

 

    
for(int i=0;i<8;i++)

    
{

        teststruct.arrf[i]
=i;

    }


 

  

    
if( fopen_s( &stream, "fread.out""w+t" ) == 0 )

    
{

        fwrite( 
&teststruct, sizeof( teststruct ), 1, stream );

        fclose( stream );

    }


    
else

        printf( 
"File could not be opened " );

    
return 0;

}


 

 

C#中读取C++中生成的文件,并填充到C#中的结构中:

对应C++结构在C#声明如下:

      读取文件到byte[]:

  [StructLayout(LayoutKind.Sequential, Pack = 1)]

        
struct TestStruct

        
{

            
float f1;

            
float f2;

            
short s1;

            
short s2;

            [MarshalAs(UnmanagedType.ByValArray, SizeConst 
= 8)]

            
float[] arrf;

        }


 

 

 

           

  FileStream fs = 

                    
new FileStream("fread.out", FileMode.Open, FileAccess.Read);

            BinaryReader r 
= new BinaryReader(fs);

            
byte[] b = r.ReadBytes((int)fs.Length);

            r.Close();

            fs.Close();

 

byte[] 转换成TestStruct:

        

 private static TestStruct GetTestStruct(byte[] b)

        
{

            IntPtr intprt 
= 

                  GCHandle.Alloc(b, GCHandleType.Pinned).AddrOfPinnedObject();

            
int isize = Marshal.SizeOf(typeof(TestStruct));

            TestStruct t 
= 

                  (TestStruct)Marshal.PtrToStructure(intprt, 
typeof(TestStruct));

            Marshal.FreeHGlobal(intprt);

 

            
return t;

        }


 

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值