Understanding the Pointer for string

Asked 2 years ago, Updated 2 years ago, 44 views

Obtain the String pointer address as follows:

var str="test";
varhandle=GChandle.Alloc(str,GCHandleType.Pined);
varptr = handle.AddrOfPinnatedObject();
Console.WriteLine("0x{0}", ptr.ToString("x8"));

What should I do to replace this pointer itself?
I don't know if rewriting the pointer is correct, but for example,

static void test (ref string str)
{
    str = "changed";
}

If you have prepared a function to pass such a string as a reference and change the value,
The pointer address is different before and after rewriting.
I want to set a new address for this pointer that references it.

I don't know exactly, but my guess is that the string type of C# is

  • Pointer indicating the address where the string length information is stored
  • Pointer indicating the address where the string value information is stored

is present and the pointer returned by the AddrOfPinnedObject is the latter

  • Pointer indicating the address where the string value information is stored

It is assumed that
A pointer indicating an address for storing the value information of the string is obtained, and
I'm looking for a way to forcefully replace the pointer itself.

Thank you for your cooperation.

c#

2022-09-30 18:22

2 Answers

Pointer indicating the address for storing string value information

As you can see in pgrho's answer, the String object contains a substantial string, so it does not retain a pointer to the string.

How can I replace this pointer itself?

Cannot be replaced because the pointer is not retained.Also, the String object is managed by GC and should not be rewritten.A forced rewrite can affect up to other variables, as shown in the following example:The same string may not be affected and the results should be considered unpredictable.

var hoge1 = "hoge";
var hoge2 = "hoge";
unsafe
{
    fixed(char*p=hoge1)
    {
        p[1] = 'a';
    }
}
Console.WriteLine($"{hoge1} and {hoge2}";
// =>hage and hage


2022-09-30 18:22

The .NET Framework string type is recorded in continuous memory in the following format:

  • String length (4-byte integer)
  • chararray (2 bytes x characters)
  • NULL characters (2 bytes)

The string pointer points to the leading char.Therefore, you can rewrite the value of an existing instance by substituting (char*)ptr)[i] within the original number of characters, but you cannot reallocate because there is no pointer to the pointer.


2022-09-30 18:22

If you have any answers or tips


© 2024 OneMinuteCode. All rights reserved.