3

我有一个 C++ 接口,它有一个公共属性“P”,它接受位值,如 5、6,7 等。它的文档说:“设置组类型的位掩码。位 5 用于 'a',位 6 用于' b'等”

我在我的 C# 类中使用这个接口,元数据中显示的这个属性“P”的类型是 VS.Net 中的“char”。

如何从我的 C# 代码将位值 6 和 7 传递给此属性?请注意,如上所述,应将“char”类型的值从 C# 传递到此 C++ 接口,因为这是在 VS.net 的元数据中显示的类型

请建议。代码:

从 VS.Net IDE 中看到的 C++ 接口定义——

[SuppressUnmanagedCodeSecurity]
    [Guid("f274179c-6d8a-11d2-90fc-00806fa6792c")]
    [InterfaceType(1)]
    public interface IAccount
    {
        char GroupType { get; set; }
    }

C#:

IAccount objAccount= new AccountClass();
((IAccount)objAccount).GroupType = ??//I need to pass char value here

谢谢。

4

2 回答 2

4

您可以使用从“字节”继承的“枚举”类型:

[Flags]
enum BitFlags : byte
{
    One = ( 1 << 0 ),
    Two = ( 1 << 1 ),
    Three = ( 1 << 2 ),
    Four = ( 1 << 3 ),
    Five = ( 1 << 4 ),
    Six = ( 1 << 5 ),
    Seven = ( 1 << 6 ),
    Eight = ( 1 << 7 )
}

void Main()
{
    BitFlags myValue= BitFlags.Six | BitFlags.Seven;

    Console.WriteLine( Convert.ToString( (byte) myValue, 2 ) );
}

输出:1100000

您需要发布有关本机方法以及如何调用它的更多信息,以便进一步提供帮助。

[SuppressUnmanagedCodeSecurity]
[Guid("f274179c-6d8a-11d2-90fc-00806fa6792c")]
[InterfaceType(1)]
public interface IAccount
{
    byte GroupType { get; set; } // char in native C++ is generally going to be 8 bits, this = C# byte
}

IAccount objAccount= new AccountClass();  

( ( IAccount ) objAccount ).GroupType = ( byte )( BitFlags.Six | BitFlags.Seven );
于 2011-06-22T10:59:34.960 回答
2

C++ 中的char类型始终为 8 位,这大概意味着您将使用 abyte来表示 C# 中的相同事物。(这假设您的 C++ 平台使用标准的 8 位字节,因为 C++char被定义为 1 个字节,但 C++“字节”不一定保证为 8 位!)

byte b = 0;
b |= 1 << 5;    // set bit 5 (assuming that the bit indices are 0-based)
b |= 1 << 6;    // set bit 6 (assuming that the bit indices are 0-based)

我不确定您如何将该值编组回您的 C++ 例程,如果这是您需要做的。

于 2011-06-22T10:57:58.933 回答