Reputation: 97
I have a C++-Dll which I am calling from a C# project. In a function I need a string as a parameter and then convert it to an unsigned char*. I am using System.String^ to convert the C#-String to a C++-String. How can I convert the String^ to an unsigned char * in C++?
I tried this but it isn't working:
void Function(String^ userInput)
{
unsigned char* msg;
strcpy((char*)msg, userInput); // Doesn't work
}
Upvotes: 0
Views: 686
Reputation: 1344
you can do it with this code:
using namespace System::Runtime::InteropServices;
const unsigned char* str = (const unsigned char*) (Marshal::StringToHGlobalAnsi(managedString)).ToPointer();
Also remeber to free the newly allocated resource with Marshal::FreeHGlobal(), when the string is no longer in use, otherwise you will have memory leak.
Upvotes: 2