Thursday, June 26, 2014

How to convert String to Byte* and pass it to Unmanaged application

Well, if you have full control over the C++ class then you can use StringToCoTaskMemAnsi and FreeCoTaskMem as I suggested. But you should place all the code inside the managed C++ class istead of doing it in C#, something like:




public ref class ManagedClass {
public:
unsigned char *data;

void SetData(String^ str) {
FreeData();
data = (unsigned char *)Marshal::StringToCoTaskMemAnsi(str).ToPointer();
}

void FreeData() {
Marshal::FreeCoTaskMem((IntPtr)data);
data = nullptr;
}

~ManagedClass() {
this->!ManagedClass();
}

!ManagedClass() {
FreeData();
}
}

You simply call SetData with the appropriate string from C#. When you no longer need the data you call Dispose (from C#) or use the delete operator (from C++) to dispose the ManagedClass object and release the native string memory.


No comments:

Post a Comment