Need to convert String^ to char *
c++-cli, char, string
Solution
Your best bet is to use `StringToHGlobalAnsi`. Here is complete code showing how its done and remembering to free the memory allocated.
using namespace System::Runtime::InteropServices;
void MethodName()
{
String^ nowString = DateTime::Now.ToString("yyyy-MM-dd-HH:mm");
IntPtr ptrToNativeString = Marshal::StringToHGlobalAnsi(nowString);
try
{
CvCapture* capture = cvCreateCameraCapture(0);
IplImage* toSave = cvQueryFrame(capture);
cvSaveImage(static_cast<char*>(ptrToNativeString.ToPointer()), toSave);
cvReleaseImage(&toSave);
cvReleaseCapture(&capture);
}
catch (...)
{
Marshal::FreeHGlobal(ptrToNativeString);
throw;
}
Marshal::FreeHGlobal(ptrToNativeString);
}
You might want to rethink using a ':' character in the filename, as I don't believe windows likes this very much.
Problem
I am using the .NET DateTime to get the current date and time. I am converting it to a string to use as part of a file name. The problem is the OpenCV command to save an image requires a char * not a string type, and DateTime will only output a String^ type. How do I make this work? Heres the code not completed ``` String^ nowString = DateTime::Now.ToString("yyyy-MM-dd-HH:mm"); IplImage* toSave; CvCapture* capture = cvCreateCameraCapture(0); toSave = cvQueryFrame( capture ); cvSaveImage(nowString, toSave); cvReleaseImage(&toSave); cvReleaseCapture(&capture); ```