dll 联合体 报错 。它在 8 偏移位置处包含一个对象字段,该字段已由一个非对象字段不正确地对齐。

gut_GIS 2015-10-27 11:36:50
c++原型
typedef struct Tag_Report{
union{
RoReport tRoReport;
EventReport tEventReport;
}report;
unsigned int nResType;
}Report;
我转为c#如下
[StructLayoutAttribute(LayoutKind.Sequential)]
public struct Report
{
public report report;
public uint nResType;

}
[StructLayoutAttribute(LayoutKind.Explicit)]
public struct report
{
[FieldOffsetAttribute(0)]
RoReport tRoReport;
[FieldOffsetAttribute(0)]
EventReport tEventReport;
}
编译没错,运行时报出:
未能从程序集“EPC, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null”中加载类型“report”,因为它在 8 偏移位置处包含一个对象字段,该字段已由一个非对象字段不正确地对齐或重叠。

有没有人会啊,各位大神们,指点指点
...全文
345 12 打赏 收藏 转发到动态 举报
写回复
用AI写文章
12 条回复
切换为时间正序
请发表友善的回复…
发表回复
IT王 2019-02-12
  • 打赏
  • 举报
回复
C#union用法注意:
[StructLayoutAttribute(LayoutKind.Explicit, Pack = 1)]
public struct report
{
[FieldOffsetAttribute(0)]
RoReport tRoReport;
[FieldOffsetAttribute(0)]
EventReport tEventReport;
}
注意:
所有的Pack = 1必不可少(包括子级以Sequence对齐的结构图),具体对齐字节数请填到Pack。

内部如包含数组,用法是:
[MarshalAs(UnmanagedType.ByValArray, SizeConst = 3)]
public EventReport[] a;

如需转换到字节流,请经过Marshal.Alloc,Marshal.Copy
gut_GIS 2015-10-28
  • 打赏
  • 举报
回复
我觉得就调用一个普通的由c++编译出的dll而已,没这么复杂的。可惜我对c语言不太会,大神们,能来点干货吗???
gut_GIS 2015-10-27
  • 打赏
  • 举报
回复
[FieldOffsetAttribute(8)] EventReport tEventReport 还是出现:未能从程序集“EPC, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null”中加载类型“report”,因为它在 8 偏移位置处包含一个对象字段,该字段已由一个非对象字段不正确地对齐。这个错误
gut_GIS 2015-10-27
  • 打赏
  • 举报
回复
RoReport和EventReport结构体如下: [StructLayoutAttribute(LayoutKind.Sequential)] public struct RoReport { public string a; public string b public int c; public uint d; public ushort e; public ushort f; public uint g; public ulong h; } [StructLayoutAttribute(LayoutKind.Sequential)] public struct EventReport { uint mm; ulong ullTime; int nSpecIndex; } [FieldOffsetAttribute(8)]的值到底是怎么确定的呢?
本拉灯 2015-10-27
  • 打赏
  • 举报
回复
[FieldOffsetAttribute(8)] EventReport tEventReport;
Poopaye 2015-10-27
  • 打赏
  • 举报
回复
结构贴全行吗?
gut_GIS 2015-10-27
  • 打赏
  • 举报
回复
感觉好复杂啊,那我该怎么写呢?给个例子吧
Poopaye 2015-10-27
  • 打赏
  • 举报
回复
引用 8 楼 gut_GIS 的回复:
你确定:结构体里如果用String必须加上MashalAsAttribute吗? 可不可以帮我写一下呀?
[MashalAs(UnmanagedType.LPTStr)] 这边不一定是LPTStr,可能是LPStr、LPWStr等等,要看你的程序编码
gut_GIS 2015-10-27
  • 打赏
  • 举报
回复
c++原型: typedef struct RoReport { char *ptTagBuf; char *ptOpBuf; int nRes; unsigned int nResType; unsigned short nOpId; unsigned short wAntId; unsigned long long ullTimestamp; } RoReport; 你确定:结构体里如果用String必须加上MashalAsAttribute吗? 可不可以帮我写一下呀?
Poopaye 2015-10-27
  • 打赏
  • 举报
回复
结构体里如果用String必须加上MashalAsAttribute
wanghui0380 2015-10-27
  • 打赏
  • 举报
回复
string??? 这个不好玩了 C++里对这个RoReport原始定义是什么,你的贴一下。string 不给size,有些玄
gut_GIS 2015-10-27
  • 打赏
  • 举报
回复

110,567

社区成员

发帖
与我相关
我的任务
社区描述
.NET技术 C#
社区管理员
  • C#
  • Web++
  • by_封爱
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告

让您成为最强悍的C#开发者

试试用AI创作助手写篇文章吧