Reputation: 1541
Is it possible to create pinned pointer in C#
like a pin_ptr
in C++/CLI
?
Upvotes: 3
Views: 3550
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 string
s 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
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