2012-07-18 60 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); 
     } 

    }