-2

I have a method in a Windows Forms Application where I get the contents from a textbox and store in a string. I would like to get the memory location where the string is stored. In a console application, this works with &stringData. But I am not able to get the memory location in this case.

This is what the function looks like:

private: System::Void button1_Click(System::Object^  sender, System::EventArgs^  e) {
    String^ myString = textBox1->Text;
    // Get memory location of myString
}
pnuts
  • 58,317
  • 11
  • 87
  • 139
jyotiska
  • 271
  • 2
  • 3
  • 8
  • That's not C++ - it's a Microsoft abomination called Managed C++/CLI or some such - please tag appropriately and fix your title. – Paul R May 06 '14 at 09:53
  • I have removed the "C++" tag from the post. – jyotiska May 06 '14 at 09:55
  • I've fixed your title for you now also. – Paul R May 06 '14 at 09:56
  • 1
    This "abomination" adds a garbage collector to C++. Pretty important to de-tune the traditional memory-think, a GC moves objects around when it collects garbage. In other words, objects like String don't have a stable memory location anymore. There are very few cases where you actually need the address, you gets lots of help from the framework to avoid it. Nobody can see *why* you need it. If you really, really need it then you can use the `pin_ptr<>` class to get one. – Hans Passant May 06 '14 at 11:35

1 Answers1

0

The string myString is a managed object. You can tell because you declared it with the ^ operator. You can't retrieve a native pointer to managed objects simply by using the address-of operator (&).

Instead, you can use pin_ptr<>. That will pin the object so that it cannot be moved by the garbage collector, as long as the pin_ptr<> is in scope.

pin_ptr<System::String> pin = &myString;
void* ptr = pin;
// do whatever you want with ptr here...

But assuming that the code in the question has not been oversimplified for the purposes of an example, I have no idea why you'd want to do that. Just create an unmanaged object in the first place, and then retrieve its address like you normally would with the & operator.

Community
  • 1
  • 1
Cody Gray - on strike
  • 239,200
  • 50
  • 490
  • 574