Skip to content

Confused about PWSTR.From(string) #9

@jonpryor

Description

@jonpryor

I'm confused about the safety (sanity?) of PWSTR.From(string?):

public unsafe static PWSTR From(string? str)
{
if (str == null)
return Null;
fixed (char* chars = str)
{
return new PWSTR(chars);
}
}

In particular the fixed block:

fixed (char* chars = str)
{
return new PWSTR(chars);
}

The fixed statement:

prevents the garbage collector from relocating a moveable variable and declares a pointer to that variable.

but that variable is only prevented from relocating within the fixed statement.

Yet here you retain the pointer value and reuse outside the fixed statement.

How does this not "interact poorly" with the GC?

var s = PWSTR.From("foo");

// GC happens, causing `foo` to move in memory

// use `s`. "boom"?

(It's probably "fine" for string constants as those are often interned, but for the output of StringBuilder.ToString()…?)

Am I missing something, or is this as horrifying as I think it is?

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions