Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Convert a 'System::String ^' to 'const char *' in vc++

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.

like image 901
devan Avatar asked Oct 06 '11 05:10

devan


People also ask

How to convert string to const char* in C++?

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 ...

How do I convert a string to a char* in Java?

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.

How do you pass a string to a function in C?

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:

How to get the current value of a string in C?

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.


2 Answers

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
like image 101
Roman R. Avatar answered Oct 04 '22 20:10

Roman R.


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));
}
like image 44
devan Avatar answered Oct 04 '22 20:10

devan