【发布时间】:2016-02-14 20:49:24
【问题描述】:
我对 C++ 和创建引用字节 [] 有疑问。
在 C# 中我的方法是:
public static void SetBitAt(ref byte[] Buffer, int Pos, int Bit, bool Value)
{
byte[] Mask = { 0x01, 0x02, 0x04, 0x08, 0x10, 0x20, 0x40, 0x80 };
if (Bit < 0) Bit = 0;
if (Bit > 7) Bit = 7;
if (Value)
Buffer[Pos] = (byte)(Buffer[Pos] | Mask[Bit]);
else
Buffer[Pos] = (byte)(Buffer[Pos] & ~Mask[Bit]);
}
我想将它翻译成 C++,但我无法获得 refworking for C++。我看到了一些关于 & 符号的东西,我尝试了这样的事情:
void SetBitAt(byte& buffer[], int Pos, int Bit, bool Value)
{
byte Mask[] = { 0x01, 0x02, 0x04, 0x08, 0x10, 0x20, 0x40, 0x80 };
if (Bit < 0) Bit = 0;
if (Bit > 7) Bit = 7;
if (Value)
{
buffer[Pos] = (byte)(buffer[Pos] | Mask[Bit]);
}
else
{
buffer[Pos] = (byte)(buffer[Pos] & ~Mask[Bit]);
}
}
然后我得到错误:
'buffer':引用数组是非法的。
那么如何更改我的 C++ 代码以使用引用数组?
编辑: 我使用这种方法设置缓冲区,但是使用这种方法时它不会改变。
其他类:
buffer = ReadDB(2); //Read the values in the DataBlock
SetBitAt(buffer, 0,0 true); //Set bit 0,0 to 1(true)
WriteDB(2, buffer); //Write the values to the Datablock
但缓冲区不会改变。它的值相同。
【问题讨论】:
-
"ref" 仅在 C++ CLR 中启用。这就是它在这里不起作用的原因。