Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
611 views
in Technique[技术] by (71.8m points)

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

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
        BYTE FirstName[NAME_SIZE];//66
        BYTE LastName[NAME_SIZE]; //66
        long Pin;
        BYTE TimeGroupIDList[IDLIST_SIZE];//10
        enum EUserKind   eUserKind;
        BYTE WarningEye;        
};

When i use this structure in my C# Application to fill this structure for User data and pass to my AddUser API it returns this Error.

Any help is appreciated. Thanks.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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];


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...