我是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);
Operator '+' cannot be applied to operands of type 'byte[]' and 'int'
时抛出了一个错误。
怎么能实现这个???? :)请帮助:)
答案 0 :(得分:2)
for(int i = 0; i < 8; i++)
{
sendBuf[i+memloc] = Convert.ToSByte(version[i]);
}
答案 1 :(得分: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;
答案 2 :(得分:0)
您可以尝试两种方式。第一种方法是使用System.Buffer.BlockCopy()
进行直接复制<强> e.g 强>
// 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);