Windows Forms – and managed strings?

I’m a MinGW kind of girl. But I do have VS installed on my PC. Because of – don’t laugh – Windows Forms. Sometimes, I need to create very, very simple CRUD-kind-of-apps. Read a  file, have some buttons with some logic, display it, create a config file, done. Single-
purpose throwaway things.
I love Windows Forms for that.
There’s just one thing.

String ^
Dear god, I HATE managed C++.
It’s not bad, but’s just not “my” C++ any more. A mean, a garbage collection?? (Well, but I understand the whole common langage thing. It’s actually quite neat, and I  did have some fun with C#, but please – is creating a c-String that hard? Because, no, I’m
not going to loop through those chars and build it myself!)

Apparently it is.

But beloved Stackoverflow knows the answer:

Use this one:

void MarshalString ( String ^ s, string& os ) {
using namespace Runtime::InteropServices;
const char* chars =
(const char*)(Marshal::StringToHGlobalAnsi(s)).ToPointer();
os = chars;

//this is the code to use the function:
string a = "test";
String ^ c = gcnew String(scheduleBox->SelectedItem->ToString());
MarshalString(c, a);
filestream << a;

(also stolen from this one:
It works. Done.


One comment

  1. […] are generated with very simple tools that help the user generate correct one (I’m using Windows Forms for that, because it’s dead simple and works), some are incredibly complicated and […]

Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: