I am trying for the first time to use Windows Forms from C++/CLI but mixing it with my unmanaged code base.
Even after reading some articles on passing values between the two I am still a little confused.
Say I have an unmanaged header file that declares:
struct Options
{
std::string text;
int value;
};
Now I have an unmanaged .cpp that does this:
int __stdcall RunManagedOptionsForm(Options& options);
void main()
{
Options options;
RunManagedOptionsForm(options);
}
Then in my managed file I have:
int __stdcall RunManagedOptionsForm(Options& options)
{
OptionsForm^ form = gcnew OptionsForm();
form->ShowDialog();
options.text= form->text; //What to do here?
options.value = form->value;
}
I have seen code like:
String^ s = gcnew String("sample string");
IntPtr ip = Marshal::StringToHGlobalAnsi(s);
const char* str = static_cast<const char*>(ip.ToPointer());
Console::WriteLine("(managed) passing string...");
NativeTakesAString( str );
Marshal::FreeHGlobal( ip );
But I am not sure how to apply it in this situation?
Also if I play around with managed code that creates std::string's etc and pass that to unmanaged code is that dangerous?
Thanks
C++/CLI interop
Started by hifive, Jun 17 2009 06:18 PM
1 reply to this topic
#1
Posted 17 June 2009 - 06:18 PM
#2
Posted 17 June 2009 - 07:38 PM
First of all, put code in
Not at all.
...[/[i][/i]code] tags to make it more readable :lol:
[quote]But I am not sure how to apply it in this situation?[/quote]
Why not? The example code clearly shows that at a certain point you have a const char *. That is something you can assign to a std::string object.
You might consider using wchar_t type strings (and thusly std::wstring) throughout your project instead. This is the character type that the .Net String class uses internally as well, so you don't have to convert your strings back and forth between UTF-16 and Ascii.
[code]std::wstring FromManagedString(System::String^ str)
{
array<wchar_t>^ chars = str->ToCharArray(); // get the array of chars
pin_ptr<wchar_t> p = &chars[0]; // pin the array and get a native pointer to the first element
return std::wstring(p, p + chars->Length); // return a newly constructed wstring using the char array
}
Quote
Also if I play around with managed code that creates std::string's etc and pass that to unmanaged code is that dangerous?
C++ addict
-
Currently working on: the 3D engine for Tomb Raider.
-
Currently working on: the 3D engine for Tomb Raider.
1 user(s) are reading this topic
0 members, 1 guests, 0 anonymous users












