方法:使用C#调用C++ memcpy实现各种参数类型的内存拷贝
using System.Runtime.InteropServices;
public class GlbWSGridDataset
{
[DllImport("msvcrt.dll", EntryPoint = "memcpy", CallingConvention = CallingConvention.Cdecl, SetLastError = false)]
public static extern void MemCopy(int[] dest, byte[] src, int count);//字节数组到整形数组的拷贝
[DllImport("msvcrt.dll", EntryPoint = "memcpy", CallingConvention = CallingConvention.Cdecl, SetLastError = false)]
public static extern void MemCopy(double[] dest, byte[] src, int count);//字节数组到double数组的拷贝
[DllImport("msvcrt.dll", EntryPoint = "memcpy", CallingConvention = CallingConvention.Cdecl, SetLastError = false)]
public unsafe static extern void MemCopy(ref GlbcwSGridFacet dest, byte[] src, int count);//注意只有结构体能这么做,class不可以
public void test()
{
string filepath = @"c:ddd.sgr";
FileStream fs = new FileStream(filepath, FileMode.Open);//初始化文件流
BinaryReader binReader = new BinaryReader(fs);
{///byte[] 转 double[]
int zcount = (grid.ni) * (grid.nj) * (grid.nk + 1);
double[] zArray = new double[zcount * 4];
System.Diagnostics.Trace.Assert(zArray != null);
int zlen = zcount * 4 * sizeof(double);
byte[] zdata = new byte[zlen];
zdata = binReader.ReadBytes(zlen);
// 调用c++的memcopy实现拷贝
MemCopy(zArray, zdata, zlen);
}
{///byte[] 转 int[]
int clrcount = (NI) * (NJ) * (NK);
clrArray = new int[clrcount];
System.Diagnostics.Trace.Assert(clrArray != null);
int len = clrcount * sizeof(int);
byte[] clrdata = new byte[len];
clrdata = binReader.ReadBytes(len);
// 拷贝整型数组
MemCopy(clrArray, clrdata, len);
}
{///byte[] 转struct
GlbcwSGridFacet bounderCellIndexs = new GlbcwSGridFacet();
// 使用Marshal.SizeOf来计算struct的大小
int len = System.Runtime.InteropServices.Marshal.SizeOf(typeof(GlbcwSGridFacet))
byte[] data= new byte[len];
System.Diagnostics.Trace.Assert(data!= null);
data= binReader.ReadBytes(len);
// 用不安全的拷贝方式memcpy 效率最快
MemCopy(ref bounderCellIndexs, data, len);
}
// 关闭文件
binReader.Close();
fs.Close();
}
}
参考 https://www.cnblogs.com/timeObjserver/p/7040966.html?utm_source=itdadao&utm_medium=referral C#调用C++ memcpy实现各种参数类型的内存拷贝 VS marshal.copy的实现 效率对比