C++/CLI interop

97087039d48b05a92c98b0d9cc4c0096
0
hifive 101 Jun 17, 2009 at 18:18

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

1 Reply

Please log in or register to post a reply.

340bf64ac6abda6e40f7e860279823cb
0
_oisyn 101 Jun 17, 2009 at 19:38

First of all, put code in

...[/[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
}

Also if I play around with managed code that creates std::string’s etc and pass that to unmanaged code is that dangerous?

Not at all.