How to get a pointer to a C# non-blittable ref struct

Viewed 393

I'm trying to pass a pointer to "ref Struct" to some C++ code via pinvoke so that it can be passed back to C# via a delegate callback (and then converted back to a ref) so as to avoid the default marshaling that occurs because the struct is non-blittable (see my other question How to to pass a C# delegate (callback) with a ref struct parameter to C++ using SWIG)

I can get a pointer to a normal struct containing non-blittable fields by using Unsafe.AsPointer. However this won't compile (CS0306) for a ref struct as shown in the code below:

public struct NormalStruct
{
    public int value;
    public string text;
}

public ref struct RefStruct
{
    public int value;
    public string text;
}

NormalStruct ns = new NormalStruct() { value = 42 };
RefStruct rs = new RefStruct() { value = 42 };

// This works   
void* nsPtr = Unsafe.AsPointer(ref ns);

// This won't compile with CS0306;
void* rsPtr = Unsafe.AsPointer(ref rs);

Is there someway to get a pointer to a ref struct - or to change the default marshaling for a type

1 Answers

I was struggling with this for a bit, but for anyone who finds this later, I was able to get this to work using this.

public void Method(ref MyStruct refStruct)
{
    fixed (MyStruct* structPointer = &refStruct)
    {
        // do something with ref struct here
    }
}
Related