How to use GetBufferSubData?

860 Views Asked by At

I am currently playing around with SharpGL but can not figure out how to use it's function GetBufferSubData in proper way.

   public void GetBufferSubData(uint target, 
                                int offset, 
                                int size, 
                                IntPtr data);

Use case situation: I already fill VBO with some data and now want to get it from there back to managed object.

My attempts have failed with FatalExecutionEngineError which, as I read, corresponds to to leaks in memory heap. But I am not sure I have a proper code for my needs.

public virtual unsafe float[] GetFromBuffer(int offset, int length)
{
    float[] output = new float[length];

    Bind();

    fixed (float* array = output)
    {
        var ptr = new IntPtr(array);

        Gl.GetBufferSubData(Id, offset, sizeof(float) * length, ptr);

        // Not needed code (fixed after answer)
        //GCHandle handle = (GCHandle) ptr;
        //output = (handle.Target as float[]);
    }

    return output;
 }

My question is how to get data back to managed object.

1

There are 1 best solutions below

0
On BEST ANSWER

The first argument to GetBufferSubData() is not the id (aka name) of the buffer, but the buffer target. You need to bind your buffer to the target first, and then use GetBufferSubData with the same target:

Gl.BindBuffer(OpenGL.GL_ARRAY_BUFFER, Id);
Gl.GetBufferSubData(OpenGL.GL_ARRAY_BUFFER, offset, sizeof(float) * length, ptr);