参阅文档(写的很清楚,但我的还是出错)
http://www.cnblogs.com/allenlooplee/archive/2004/12/25/81917.html问题是这样的:在C++DLL的接口函数中要传递一个结构,此结构中包括一个联合,我用C#来写这个结构并模拟这个联合,但老出错,请大家帮忙!C++结构声明原型
typedef struct cmppe_packet cmppe_packet;
struct cmppe_packet{
cmppe_head pk_head; /*接收到的包头信息*///结构
dpl_int32_t result; /*表明解析该包的结果*/ //无符号INT型
union{//联合
cmppe_deliver pk_deliver;
cmppe_login_resp pk_login_resp;
cmppe_submit_resp pk_submit_resp;
}pk_data;
};
我用C#写的模拟:
[StructLayout(LayoutKind.Sequential)]
public struct cmppe_packet
{
public cmppe_head pk_head; /*接收到的包头信息*///结构
public int result; /*表明解析该包的结果*/ 
public pk_data_struct pk_data;
}
     /// <summary>
/// C#结构实现联合的方法 cmppe_packet
/// </summary>
[StructLayout(LayoutKind.Explicit, Size=1000)]//
public struct pk_data_struct
{
[FieldOffset(0)]
public cmppe_deliver pk_deliver;
[FieldOffset(0)]
public cmppe_login_resp pk_login_resp;
[FieldOffset(0)]
public cmppe_submit_resp pk_submit_resp;
}
作为参数传递此结构是用 REF 引用 类型的。现在在执行时出现如下错误。其他信息: 因为格式无效,未能从程序集 esp, Version=1.0.2060.400, Culture=neutral, PublicKeyToken=null 中加载类型 esp.pk_data_struct。

解决方案 »

  1.   

    Interop and Unions
    http://blogs.msdn.com/jaredpar/archive/2005/05/13/417263.aspx
      

  2.   

    把结构换成类试试,如果ref不行,改用[In,Out]试试
      

  3.   

    NET does not directly support unions but you can use some Marshal magic to get them working.
      

  4.   

    union Foo{   int a;   float b;}==========================================》 [StructLayout(LayoutKind.Explicit)]public struct ManagedFoo{   [FieldOffset(0)] int a;   [FieldOffset(0)] float b;}
      

  5.   

    C# 我不了解
    在 VB.NET 中实现好像是用 OffSet 特性
      

  6.   

    将联合用到类中,效果似乎更好一些。
    就是用类替代结构来调用API,问题相对少一些。
      

  7.   

    楼主的问题通过上面的方式我并没有找到答案,但通过其他方式解决了[具体问题及更好的解决办法还有待C++/C#高手解决]:将
    [ DllImport( "api.dll", CharSet=CharSet.Ansi)]
    public static extern int cmpp_recv([MarshalAs(UnmanagedType.LPStruct)] conn_desc conn , [MarshalAs(UnmanagedType.LPStruct)] cmppe_packet cp,char is_break,ref int seq);//@@无符号char int
    更改为
    [ DllImport( "api.dll", CharSet=CharSet.Ansi)]
    public static extern int cmpp_recv([MarshalAs(UnmanagedType.LPStruct)] conn_desc conn , IntPtr cp,char is_break,ref int seq);//@@无符号char int然后写下列函数:
    private int CmppRecv(conn_desc conn, cmppe_packet cp,char is_break,ref int seq)
    {
    int strusize = System.Runtime.InteropServices.Marshal.SizeOf(cp.GetType());
    IntPtr pp =  System.Runtime.InteropServices.Marshal.AllocHGlobal(strusize);
    byte[] ppp = new byte[strusize];
    int stat = esp.cmpp_recv(conn,pp,is_break,ref seq);//从ISMG服务器接收数据包,并对接收的数据包进行解析
    System.Runtime.InteropServices.Marshal.Copy(pp,ppp,0,strusize);
    System.Runtime.InteropServices.Marshal.PtrToStructure(pp,cp);
    System.Runtime.InteropServices.Marshal.FreeHGlobal(pp);
    return stat;
    }
    最后调用stat = esp.cmpp_recv(conn,cp,'0',ref aa);更改为stat=CmppRecv(conn,cp,'0',ref aa);即可。
      

  8.   

    一切OK了!
    谢谢  malingxian(马领先) 在MSN上的帮助和大家的关注 我的胜利是属于你们的。
    有空我会整合一篇文章来帮助以后搞这块的人们.....