将C++结构数组编组到C#中通常涉及几个步骤,包括定义相应的数据结构、序列化和反序列化数据。以下是一个详细的步骤说明和相关代码示例:
假设我们有一个简单的C++结构体和一个数组:
#include <iostream>
#include <vector>
#include <fstream>
struct Person {
char name[50];
int age;
};
void WriteStructArrayToFile(const std::vector<Person>& people, const char* filename) {
std::ofstream outFile(filename, std::ios::binary);
for (const auto& person : people) {
outFile.write(reinterpret_cast<const char*>(&person), sizeof(Person));
}
}
在C#中,我们需要定义一个对应的结构体,并使用序列化库来读取二进制文件:
using System;
using System.IO;
using System.Runtime.InteropServices;
[StructLayout(LayoutKind.Sequential, CharSet = CharSet.Ansi)]
public struct Person
{
[MarshalAs(UnmanagedType.ByValTStr, SizeConst = 50)]
public string Name;
public int Age;
}
public class Program
{
public static void Main()
{
string filename = "people.bin";
var people = ReadStructArrayFromFile(filename);
foreach (var person in people)
{
Console.WriteLine($"Name: {person.Name}, Age: {person.Age}");
}
}
private static Person[] ReadStructArrayFromFile(string filename)
{
using (FileStream fs = new FileStream(filename, FileMode.Open, FileAccess.Read))
using (BinaryReader reader = new BinaryReader(fs))
{
int count = (int)(fs.Length / Marshal.SizeOf(typeof(Person)));
Person[] people = new Person[count];
for (int i = 0; i < count; i++)
{
people[i] = reader.ReadStruct<Person>();
}
return people;
}
}
}
#pragma pack
指令或在C#中使用StructLayout
属性来控制对齐。#pragma pack
指令或在C#中使用StructLayout
属性来控制对齐。通过以上步骤和代码示例,可以实现C++结构数组到C#的有效编组和传输。
领取专属 10元无门槛券
手把手带您无忧上云