2014-06-13 80 views
2

所以我有這個方法返回一個字符指針:字符指針字符數組

Private: char* currentSelectedDevice() 
     { 
      String^ comboboxText = counterComboBox->Text; 
      marshal_context^context = gcnew marshal_context(); 
      char* temp; 
      cont char* convertedString = context->marshal_as<const char*>(comboboxText); 
      temp = const_cast<char *>(convertedString); 
      char* oneCounterPort = strtok (temp, " ="); 
      return oneCounterPort; 
     } 

我試圖做到的,是這種方法複製到一個字符數組。我正在考慮使用for循環,但沒有按照我的意願工作。那我該怎麼做?

我在想這樣的事情可能工作:

char temp[sizeof(currentSelectedDevice())] = currentSelectedDevice(); 
+0

你爲什麼還要用'char *'打擾?你應該繼續使用'System :: String'或者使用'std :: string'或'CString'。那麼你不必擔心內存分配和字符串複製。 – crashmstr

+0

@crashmstr請告訴我如何將字符串^轉換爲字符數組。 – Thealon

+0

不,因爲你真的不需要(或者至少你不告訴我們你將如何使用這個和*爲什麼*它必須是一個char []')。你應該使用'System :: String ^',或者如果你需要與C++代碼交互,'std :: string str = marshal_as (counterComboBox-> Text);'。 – crashmstr

回答

1

您可以使用Marshal::Copy。你functoin應該是這樣的:

#include <stdlib.h> // In case you use C (for malloc() access) 

// C++/CLI function 
char * currentSelectedDevice() 
{ 
    String^ comboBoxText = counterComboBox->Text; 

    // Allocate unmanaged memory: 
    char *result = (char*)malloc(comboBoxText->Length); 

    // Copy comboBoxText to result: 
    Marshal::Copy(comboBoxText ->ToCharArray(), 0, IntPtr((char*) result), comboBoxText->Length); 

    return result; 
} 

它複製從位置0comboBoxTextToCharArray()這裏的調用)的內容comboBoxText.Lengthresult

然後調用C函數將例如可以像這樣使用它:

// Calling C function 
void read_combo_box_text() 
{ 
    // Get text: 
    char * cbxText = currentSelectedDevice(); 

    // .. Do something with it 

    // Free (if don't needed anymore) 
    free(cbxText); 
} 

希望這會有所幫助。

注:如果爲C++做到這一點並不包括stdlib.hdelete[]通過newfree()更換malloc()

+0

你能給我一個easyer的例子嗎? – Thealon

+0

它說:如果我試圖複製它,16個重載中沒有一個可以轉換參數類型。 – Thealon

+0

@Thealon你不明白什麼?您是否閱讀過「Marshal :: Copy'的文檔,並且您傳遞了正確的參數? – displayname