开发者

Assigning pointer to a CLR type to void* using unsafe?

Is there any way to assign a pointer to a CLR type to a void* in a C# unsafe block?

var bar = 1;
var foo = new Foo();

unsafe
{
    void* p1 开发者_StackOverflow社区= &bar;
    void* p2 = &foo; // fails at compile time
}

Or this only possible using C++/CLI:

System::Text::StringBuilder^ sb = gcnew System::Text::StringBuilder();
void* p1 = &sb; 

Can't find any way to make it work in C#


According to the MSDN documentation:

Any of the following types may be a pointer type:

  • sbyte, byte, short, ushort, int, uint, long, ulong, char, float,
    double, decimal, or bool.
  • Any enum type.
  • Any pointer type.
  • Any user-defined struct type that contains fields of unmanaged types only.

There's no way to have a pointer to an instance of a class (e.g. pointer to an instance of System.Text.StringBuilder), although you can have a pointer to a class member in the fixed context, as in the following code:

class Test
{
static int x;
int y;
unsafe static void F(int* p) {
    *p = 1;
}
static void Main() {
    Test t = new Test();
    int[] a = new int[10];
    unsafe {
        fixed (int* p = &x) F(p);
        fixed (int* p = &t.y) F(p); // pointer to a member of a class 
        fixed (int* p = &a[0]) F(p);
        fixed (int* p = a) F(p);
    }
}
}


To get a pointer to a managed object, it must be fixed so that the GC knows not to move the object around.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜