Konstantin Zadiran
Konstantin Zadiran

Reputation: 1541

Is it possible to create pinned pointer in C#?

Is it possible to create pinned pointer in C# like a pin_ptr in C++/CLI?

Upvotes: 3

Views: 3550

Answers (2)

xanatos
xanatos

Reputation: 111870

While in C# there is the fixed keyword, and you can use the System.GCHandle struct, there is nothing that has the "power" of pin_ptr<>. With pin_ptr<> you can pin any managed object, while with fixed you are limited to pinning strings or array of value types that don't contain reference types. So you can pin an int[], or a MyEnum[], or a MyStructWithoutReferenceTypes[], but not a MyClassType or a MyClassType[].

Upvotes: 1

Gy&#246;rgy Kőszeg
Gy&#246;rgy Kőszeg

Reputation: 18013

The general solution:

GCHandle handle = GCHandle.Alloc(myObject, GCHandleType.Pinned);
try
{
    IntPtr myPinnedPointer = handle.AddrOfPinnedObject();
    // use myPinnedPointer for your needs
}
finally
{
    handle.Free();
}

Special cases:

If your object is an array of a struct or is a string, and you are allowed to used unsafe code in your project, you can use the fixed context:

unsafe
{
    fixed (char* myPinnedPointer = myString)
    {
        // use myPinnedPointer for your needs
    }
}

Upvotes: 1

Related Questions