Error : Type could not be marshaled because the length of an embedded array instance does not match the declared length in the layout

后端 未结 2 1672
旧巷少年郎
旧巷少年郎 2021-01-21 01:10

i am using a COM dll in my C# Project. I have one USERINFO Structure in my COM dll which looks like :

struct USERINFO
{
        BYTE UserID[USER_ID_SIZE];//42
           


        
相关标签:
2条回答
  • 2021-01-21 01:18

    C# does not support fixed-length arrays embedded in a struct (except in an unsafe context) so your C structure is probably being marshalled into a C# structure something like this:

    struct USERINFO
    {
        MarshalAs(UnmanagedType.ByValArray, SizeConst = 42)
        BYTE[] UserID;
        MarshalAs(UnmanagedType.ByValArray, SizeConst = 66)
        BYTE[] FirstName;
        // etc.
    };
    

    Note that the members are references to arrays, not embedded arrays.

    For the marshalling to work the arrays have to be exactly the right length (or maybe at least the right length, I forget). For example, UserID should be initialised with userInfo.UserID = new byte[42];

    0 讨论(0)
  • 2021-01-21 01:36

    I had a similar problem once and it's been solved by adding a constructor for the struct:

        struct A
        {
          public A(int b, int c)
          {
            B = b;
            C = c;
          }
    
          public int B;
          public int C
        }
    

    worth trying!

    0 讨论(0)
提交回复
热议问题