Can't I declare a pointer variable to my own class object like below?
static void Main() {
MyClass myClass = new MyClass();
unsafe {
fixed (MyClass* pMyClass = &myClass) {
/// Do Somthing here with pMyClass..
}
}
}
This page explains why: https://msdn.microsoft.com/en-us/library/y31yhkeb.aspx
C# does not allow pointers to references:
A pointer cannot point to a reference or to a struct that contains references, because an object reference can be garbage collected even if a pointer is pointing to it. The garbage collector does not keep track of whether an object is being pointed to by any pointer types.
You could argue that the fixed
keyword should allow this because it would stop the GC from collecting the object. This may be true, but consider this case:
class Foo {
public SomeOtherComplicatedClassAllocatedSeparatley _bar;
}
unsafe void Test() {
Foo foo = new Foo();
foo._bar = GetComplicatedObjectInstanceFromSomePool();
fixed(Foo* fooPtr = &foo) {
// what happens to `_bar`?
}
}
The fixed
keyword cannot overreach into members of whatever has been dereferenced, it has no authority to pin the reference-member _bar
.
Now arguably it still should be possible to pin an object that does not contain other reference-members (e.g. a simple POCO) and it is possible to pin a String
instance, but for some reason the C# language designers just decided to prohibit pinning object instances.