Jimmy
Jimmy

Reputation: 2106

Passing bit value from C#

I've a C++ interface having a public property "P" which accepts bit value like 5, 6,7 etc. Its documentation says:"Set bit mask of group type. Bit 5 is for 'a', Bit 6 is for 'b',etc."

Am using this interface in my C# class and the type of this property "P" shown in the metadata is "char" in VS.Net.

How do I pass the bit value of 6 and 7, to this property from my C# code? Please note that, as mentioned above, a value of type "char" should be passed from C# to this C++ interface, as this is the type which is shown in the metadata in VS.net

Please suggest. Code:

C++ interface definition as seen from VS.Net IDE--

[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

Thanks.

Upvotes: 3

Views: 671

Answers (2)

LukeH
LukeH

Reputation: 269678

The char type in C++ is always 8 bits, which presumably means that you'd use a byteto represent the same thing in C#. (This assumes that your C++ platform uses standard 8-bit bytes, since a C++ char is defined as being 1 byte, but a C++ "byte" isn't necessarily guaranteed to be 8 bits!)

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)

I'm not sure how you'd marshal that value back to your C++ routine, if that's what you need to do.

Upvotes: 2

Brandon Moretz
Brandon Moretz

Reputation: 7641

You can use a "Enum" type which inheres from "byte":

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

Output: 1100000

You need to post more information on the native method and how you're invoking it in order to help further.

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

Upvotes: 4

Related Questions