我正在开发一个 C# CE 应用程序来从 C++ 程序创建的二进制文件中读取数据以进行项目验证。
下面是C++程序的编码。。
// File Name: Ean2an.bin which is created by struct
struct EAN2AN_TYPE
{
__int64 ean:40; // 5 bytes, up to 12 digits
__int64 rec_no:24; // 3 bytes rec no in the c_ItemMaster File, up to 16 million records
};
// After bind data to struct, wil create the binary file
bool CreateBin_EAN2AN_TYPE()
{
if(mn_RecordCount_EAN2AN_TYPE == 0) return false;
FILE *binfile;
qsort(mc_EAN2AN_TYPE, mn_RecordCount_EAN2AN_TYPE, sizeof(struct EAN2AN_TYPE), qsort_EAN2AN_TYPE);
try
{
binfile = fopen(ms_Path_EAN2AN_TYPE, "wb");
fwrite(&mc_EAN2AN_TYPE, sizeof(struct EAN2AN_TYPE), mn_RecordCount_EAN2AN_TYPE, binfile);
}
catch(Exception ^ex)
{
TaskProgramLibrary::Message::ERR("Create EAN2AN_TYPE.bin fail!\r\n " + ex->Message);
}
finally
{
fclose(binfile);
mdw_FileSize_EAN2AN_TYPE = FileSize(ms_Path_EAN2AN_TYPE);
}
return true;
}
我尝试使用二进制读取(基于位置)读取数据并使用 bitconverter 转换为 int64 或使用 Marshal.PtrToStructure,但返回值不正确。然后我尝试从文件中读取 5 个字节而不是 8 个字节,但返回的值仍然不正确。
Below is the written C# coding
//Struct created in C#
[StructLayout(LayoutKind.Sequential)]
public struct EAN2AN_TYPE
{
[MarshalAs(UnmanagedType.I8)]
public Int64 ean;
[MarshalAs(UnmanagedType.I8)]
public Int64 rec_no;
}
//The ways i tried to read in C#
//1.Read Int64 by Binary
private void ReadByBinary()
{
using (BinaryReader b = new BinaryReader(_fs))
{
while (b.PeekChar() != 0)
{
Int64 x = b.ReadInt64();
Console.WriteLine(x.ToString());
}
}
}
//2.Using Marshal to convert the Intptr to struct's field type
private object ReadByMarshal(Type iType)
{
_oType = iType;// typeof(System.Int64);
byte[] buffer = new byte[Marshal.SizeOf(_oType)];
//byte[] buffer = new byte[5];
object oReturn = null;
try
{
_fs.Read(buffer, 0, buffer.Length);
GCHandle handle = GCHandle.Alloc(buffer, GCHandleType.Pinned);
oReturn = Marshal.PtrToStructure(handle.AddrOfPinnedObject(), _oType);
handle.Free();
return oReturn;
}
catch (Exception ex)
{
throw ex;
}
}
//3. Use Binary and use bit converter to convert to Int64
private void ReadByBinaryAndUseBitConverter()
{
using (BinaryReader b = new BinaryReader(_fs))
{
byte[] x = b.ReadBytes(8);
Int64 y = BitConverter.ToInt64(x, 0);
Console.WriteLine(y);
byte[] x2 = b.ReadBytes(8);
Int64 y2 = BitConverter.ToInt64(x2,0);
Console.WriteLine(y2);
}
}
//4. Use Marshal and convert to struct
public EAN2AN_TYPE GetStructValue()
{
byte[] buffer = new byte[Marshal.SizeOf(typeof(EAN2AN_TYPE)];
EAN2AN_TYPE oReturn = new EAN2AN_TYPE();
try
{
//if (EOF) return null;
_fs.Read(buffer, 0, buffer.Length);
GCHandle handle = GCHandle.Alloc(buffer, GCHandleType.Pinned);
IntPtr rawDataPtr = handle.AddrOfPinnedObject();
oReturn = (EAN2AN_TYPE)Marshal.PtrToStructure(rawDataPtr, typeof(EAN2AN_TYPE));
handle.Free();
if (_fs.Position >= _fs.Length)
Close();
return oReturn;
}
catch (Exception ex)
{
throw ex;
}
}
编辑:上传二进制文件的图像
编辑:C#程序读取的前8个字节值
编辑器显示的二进制数据
有人知道吗?
提前致谢