Object^ and const char*

Hi,

Here's the problem. I got this piece of code:

1
2
3
Object^ myObj = gcnew Object();
myObj = "Something";
myForm->myList->Items->Add(myObj);


And it's working. Probably with some operator overload I'm
passing the const char* data to Object's text propertie, I guess.
And that is, in part, my question. The "Something" IS a const char* right?

Because when I do this:

1
2
3
4
const char myChar[] = "Something else";
Object^ myObj = gcnew Object();
myObj = myChar;
myForm->myList->Items->Add(myObj);


I got the following error:


1>c:\users\kalkas\documents\visual studio 2008\projects\hooking\hooking\Form1.h(135) : error C2440: '=' : cannot convert from 'char *' to 'System::Object ^'
1>        No user-defined-conversion operator available, or
1>        Cannot convert an unmanaged type to a managed type


What is happening there, I don't understand.
I know for sure that "Something" is const char* because I used this
in other programs. Example, I have a function in whose argument list
a put a const char* variable and when I pass values to the function I am
either writing what I want in double quotation marks or just pass another
pre-initialized const char* variable. It's the same!
What's the problem?
This is C++/CLI, not C++, but what I'm guessing is that string literals are of a special type that both can be converted implicitly to 'const char *', and are derived from System::Object.
If you try to do this, it will probably not work, either:
1
2
Object^ myObj = gcnew Object();
myObj = (const char *)"Something";
Yes I tried that and did not worked.

But I figured a solution. I discover that you can pass the cons char* from the
the String constructor during the creation of the String and pass it to the Object^. For later use I don't know. Note that when I say String I mean System::String. There is also the
std::string. The second is much more compatible with the const char* but not
compatible with the Object^.
I figured that when you write something in double quotation marks it behaves as
System::String. That's why it worked the first time.
Anyhow, thank you for your time.

1
2
3
4
5
const char myChar[] = "Something else";
Object^ myObj = gcnew Object();
System::String myString = gcnew String(myChar);
myObj = myString;
myForm->myList->Items->Add(myObj);
Last edited on
Topic archived. No new replies allowed.