c# - 导入到 C# 时,有什么方法可以修复 COM 结构成员的顺序吗?

标签 c# c++ com com-interop idl

我在C++项目的.idl文件中定义了一个struct,该struct包含一个VARIANT成员。

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

    int                 Type;
    VARIANT             DateTime;
    float               Result;
};

界面是:

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

然后我通过“添加引用”将这个结构导入到 C# 项目中,但是成员顺序发生了变化。它看起来像这样:

namespace ASLib
{    
    [Guid("C42A456C-C139-4339-A023-F9458C8A7386")]
    public struct TEST_STRUCT
    {
        public object DateTime;
        public int Type;
        public float Result;
    }
}

DateTime 成员的顺序在 C# 中更改为第一个,当 C# 调用该接口(interface)时会导致 Interop.COMException "Bad variable type"。

那么有什么方法可以固定 COM idl 文件中结构成员的顺序吗?非常感谢。

最佳答案

您可以通过 StructLayout 手动修复结构布局.

FieldOffset 属性添加到生成的字段。

大概是这样的:

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

关于c# - 导入到 C# 时,有什么方法可以修复 COM 结构成员的顺序吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7709960/

相关文章:

c# - 将值从一种形式传递到另一种形式

c++ - 具有构造函数类型转换和转换运算符的转换序列

.net - "Failed to import the ActiveX control"在 Visual Studio 2013

c++ - 使用构造函数的术语是什么?

c# - 获取现场书签

c# - C#中的字符串排序问题

c# - 为什么 Intellisense 看到命名空间,而编译器却看不到?

c++ - Callable 概念和 std::is_function 类型特征有什么区别?

c++ - 为什么不带参数调用 basic_string::substr?

c# - WebApi DI Autofac - 确保 Controller 具有无参数公共(public)构造函数