How can I convert a 'System::String ^' to 'const char *' in vc++?
My code:
String ^Result1= "C:/Users/Dev/Desktop/imag.jpg";
IplImage *img1 = cvLoadImage(Result1, 1);
if I do like above it will generate following error.
error C2664: 'cvLoadImage' : cannot convert parameter 1 from 'System::String ^' to 'const char *'
Please help me.
Convert std::string to const char* in C++ 1. Using string::c_str function We can easily get a const char* from the std::string in constant time with the help of... 2. Using string::data function We can also call the string::data function on a std::string object to get const char*. 3. Using ...
This article discusses several ways to convert from System::String* to char* by using the following: PtrToStringChars gives you an interior pointer to the actual String object.
If you just want to pass a std::string to a function that needs const char* you can use std::string str; const char * c = str.c_str (); If you want to get a writable copy, like char *, you can do that with this:
These formats are C style strings. We have a function called c_str (). This will help us to do the task. It returns a pointer to an array that contains a null-terminated sequence of characters (i.e., a C-string) representing the current value of the string object.
It's like this: How to convert from System::String* to Char* in Visual C++
System::String ^ str = "Hello world\n";
//method 1
pin_ptr<const wchar_t> str1 = PtrToStringChars(str);
wprintf(str1);
//method 2
char* str2 = (char*)Marshal::StringToHGlobalAnsi(str).ToPointer();
printf(str2);
Marshal::FreeHGlobal((IntPtr)str2);
//method 3
CString str3(str);
wprintf(str3);
//method 4
#if _MSC_VER > 1499 // Visual C++ 2008 only
marshal_context ^ context = gcnew marshal_context();
const char* str4 = context->marshal_as<const char*>(str);
puts(str4);
delete context;
#endif
This is work for me.
void MarshalString ( String ^ s, string& os ) {
using namespace Runtime::InteropServices;
const char* chars =
(const char*)(Marshal::StringToHGlobalAnsi(s)).ToPointer();
os = chars;
Marshal::FreeHGlobal(IntPtr((void*)chars));
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With