Reputation: 1945
So I have this method that returns a char pointer:
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;
}
What I'm trying to achieve is to copy this method to a char array. I was thinking of using a for loop but that didn't work out as I wanted. So how can I do this?
I was thinking something like this might work:
char temp[sizeof(currentSelectedDevice())] = currentSelectedDevice();
Upvotes: 2
Views: 984
Reputation: 25397
You can use Marshal::Copy
. Your functoin would look like this:
#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;
}
It copies the content of comboBoxText
(note the call of ToCharArray()
here) from location 0
to comboBoxText.Length
into result
.
The calling C
function will then e.g. can use it like this:
// 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);
}
Hope this helps.
Note: If you do this for C++
don't include stdlib.h
and replace malloc()
by new
and free()
by delete[]
.
Upvotes: 1