正在从C#传递位值

Passing bit value from C#

本文关键字:      更新时间:2023-10-16

我有一个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

谢谢。

您可以使用源自"byte"的"Enum"类型:

[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 );

C++中的char类型总是8位,这可能意味着您将使用byte来表示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++例程。

相关文章:
  • 没有找到相关文章