5

我是一名 C++ 开发人员,最近开始研究 WPF。好吧,我在我的应用程序中使用 Array.Copy() ,看起来我无法完全获得所需的结果。

我在我的 C++ 应用程序中完成了如下操作:

static const signed char version[40] = {
'A', 'U', 'D', 'I', 'E', 'N', 'C', 'E',   // name
 0 ,  0 ,  0 ,  0 ,  0 ,  0 ,  0 ,  0 ,   // reserved,  firmware size
 0 ,  0 ,  0 ,  0 ,  0 ,  0 ,  0 ,  0 ,   // board number
 0 ,  0 ,  0 ,  0 ,  0 ,  0 ,  0 ,  0 ,   // variant, version, serial
 0 ,  0 ,  0 ,  0 ,  0 ,  0 ,  0 ,  0     // date code, reserved
};

unsigned char sendBuf[256] = {};
int memloc = 0;
sendBuf[memloc++] = 0;
sendBuf[memloc++] = 0;

// fill in the audience header
memcpy(sendBuf+memloc, version, 8); // the first 8 bytes
memloc += 16; // the 8 copied, plus 8 reserved bytes

我在我的 WPF (C#) 应用程序中做了类似的操作,如下所示:

Byte[] sendBuf = new Byte[256];

char[] version = 
        {
                'A', 'U', 'D', 'I', 'E', 'N', 'C', 'E',         // name
                '0', '0', '0', '0', '0', '0', '0', '0' ,        // reserved,  firmware size
                '0', '0', '0', '0', '0', '0', '0', '0' ,        // board number
                '0', '0', '0', '0', '0', '0', '0', '0' ,        // variant, version, serial
                '0', '0', '0', '0', '0', '0', '0', '0'          // date code, reserved
        };

// fill in the address to write to -- 0
        sendBuf[memloc++] = 0;
        sendBuf[memloc++] = 0;

        // fill in the audience header
        Array.Copy(sendBuf + memloc, version, 8);   // the first 8 bytes
        memloc += 16;

但它给我一个错误Array.Copy(sendBuf + memloc, version, 8);as Operator '+' cannot be applied to operands of type 'byte[]' and 'int'

怎么能做到这一点????:) 请帮忙 :)

4

3 回答 3

2
for(int i = 0; i < 8; i++)
{
    sendBuf[i+memloc] = Convert.ToSByte(version[i]);
}
于 2012-10-30T04:57:42.300 回答
1

为你翻译。解释是内联的。

var sendBuf = new byte[256];

// char in C# is a UTF-16 character (at least 2 bytes). Use byte[] here instead.
byte[] version = 
        {
                (byte)'A', (byte)'U', (byte)'D', (byte)'I', (byte)'E', (byte)'N', (byte)'C', (byte)'E',         // name
                0, 0, 0, 0, 0, 0, 0, 0,        // reserved,  firmware size
                0, 0, 0, 0, 0, 0, 0, 0,        // board number
                0, 0, 0, 0, 0, 0, 0, 0,        // variant, version, serial
                0, 0, 0, 0, 0, 0, 0, 0         // date code, reserved
        };

int memloc = 0;

sendBuf[memloc++] = 0;
sendBuf[memloc++] = 0;

// C# doesn't allow pointer arithmetic with arrays. memcpy's signature is also reversed.
Array.Copy(
   version,     // Source
   0,           // Index of Source
   sendBuf,     // Destination
   memloc,      // Index of Destination
   8);          // The first 8 bytes
memloc += 16;
于 2012-10-30T06:32:25.690 回答
0

您可以尝试两种方法。第一种方法是使用 System.Buffer.BlockCopy() 直接复制

例如

// fill in the audience header
Buffer.BlockCopy(version, memloc, sendBuf, 0, 8);   // the first 8 bytes

另一种方法是使用 System.Text.Encoding 命名空间从 char[] 获取所有字节。

sendBuf = System.Text.Encoding.ASCII.GetBytes(version);
于 2012-10-30T05:56:00.423 回答