2012-07-18 62 views
1

我真的感觉像是一个dufus。我已经阅读了一堆关于如何做到这一点的文章,但我似乎无法使其工作。我正在试图将一个Ascii字符串复制到一个字节数组。以下是我迄今尝试的两件事。两者都不能工作:C#将字符串复制到字节缓冲区

public int GetString (ref byte[] buffer, int buflen) 
{ 
    string mystring = "hello world"; 

    // I have tried this: 
    System.Text.UTF8Encoding encoding = new System.Text.UTF8Encoding(); 
    buffer = encoding.GetBytes(mystring); 

    // and tried this: 
    System.Buffer.BlockCopy(mystring.ToCharArray(), 0, buffer, 0, buflen); 
    return (buflen); 
} 

有人可以告诉我如何做到这一点吗?谢谢。

+1

什么是“没有一个作品”意思?输出是什么? – Jon 2012-07-18 10:48:04

回答

3

如果缓冲区足够大,你可以只写它直接:

encoding.GetBytes(mystring, 0, mystring.Length, buffer, 0) 

但是,您可能需要先检查长度;测试可能是:

if(encoding.GetMaxByteCount(mystring.length) <= buflen // cheapest first 
    || encoding.GetByteCount(mystring) <= buflen) 
{ 
    return encoding.GetBytes(mystring, 0, mystring.Length, buffer, 0) 
} 
else 
{ 
    buffer = encoding.GetBytes(mystring); 
    return buffer.Length; 
} 

后,有无关,因为你已经通过buffer出由ref。我个人认为嫌疑人这个ref是个不错的选择。有没有必要BlockCopy这里,除非你是从一个临时缓冲区拷贝,即

var tmp = encoding.GetBytes(mystring); 
// copy as much as we can from tmp to buffer 
Buffer.BlockCopy(tmp, 0, buffer, 0, buflen); 
return buflen; 
+0

谢谢,马克,但我得到这个错误:“错误CS0103:名称'编码'在当前上下文中不存在' – 2012-07-18 11:34:18

+0

@Neilw来自你的问题...'System.Text.UTF8Encoding encoding = new System。 Text.UTF8Encoding();'(尽管公平,var encoding = Encoding.UTF8;'会更容易) – 2012-07-18 11:35:04

+0

Doh!那醒了。只是拼写错误。谢谢! – 2012-07-18 11:47:12

0

也许有人需要像strcpy的标准C代码的功能转换为C#

void strcpy(ref byte[] ar,int startpoint,string str) 
    { 
     try 
     { 
      int position = startpoint; 
      byte[] tempb = Encoding.ASCII.GetBytes(str); 
      for (int i = 0; i < tempb.Length; i++) 
      { 
       ar[position] = tempb[i]; 
       position++; 
      } 
     } 
     catch(Exception ex) 
     { 
      System.Diagnostics.Debug.WriteLine("ER: "+ex.Message); 
     } 

    }