开发者

Is there any way to fix the order of COM struct members when importing to C#?

I defined a struct in .idl file of C++ project, and the struct contained one VARIANT member.

[uuid(C42A456C-C139-4339-A023-F9458C8A7386)]
struct TEST_STRUCT
{

    int                 Type;
    VARIANT             DateTime;
    float               Result;
};

The interface is:

[id(1), helpstring("Test1")] HRESULT Test1([in] int nID, [out, retval] SAFEARRAY(struct TEST_STRUCT)* ppVal);

Then I imported this struct into C# project via "Add Reference", but the member order was changed. It looks like this:

namespace ASLib
{    
    [Guid("C42A456C-C139-4339-A023-F9458C8A7386")]
    public struct TEST_STRUCT
    {
        public ob开发者_开发百科ject DateTime;
        public int Type;
        public float Result;
    }
}

The order of DateTime member was changed to first in C#, it caused an Interop.COMException "Bad variable type" when C# calls that interface.

So is there any way to fix the order of struct members in COM idl file? Thanks a lot.


You can fix the struct layout by hand via StructLayout.

Add the FieldOffset attribute to the generated fields.

It'll probably be something like:

public struct TEST_STRUCT
{
    [FieldOffset(4)]
    public object DateTime;
    [FieldOffset(0)]
    public int Type;
    [FieldOffset(8)]
    public float Result;
}
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜