Search code examples
c#unsafe

C# Convert object to unsafe void*


I'm trying to convert an object to an unsafe void*. Here's an example :

public static void glBufferData(uint target, ulong size, object data, uint usage)
{
    _glBufferData(target, size, data, usage);
}

Here are the parameters of _glBufferData :

uint target, ulong size, void* data, uint usage

I'm passing this object :

float[] positions =
{
    -0.5f, -0.5f,
    0.0f, 0.5f,
    0.5f, -0.5f
};

I tried this but it didn't work.

fixed (void* ptr = &data)
{
}

My class is unsafe by the way.
How can I do that ?


Solution

  • You cannot take the address of a variable of type object.

    Change the type of the data parameter from object to float[] and use fixed to obtain the address of the first array element:

    private static extern void _glBufferData(uint target, ulong size, void* data, uint usage);
    
    public static void glBufferData(uint target, ulong size, float[] data, uint usage)
    {
        fixed (float* ptr = &data[0])
        {
            _glBufferData(target, size, ptr, usage);
        }
    }
    

    You can also try changing void* to float[] in the signature of the _glBufferData method, which would eliminate the need to use fixed:

    private static extern void _glBufferData(uint target, ulong size, float[] data, uint usage);
    
    public static void glBufferData(uint target, ulong size, float[] data, uint usage)
    {
        _glBufferData(target, size, ptr, usage);
    }