Writing to Persistent Mapped Buffers

Started by
1 comment, last by hgoel0974 9 years ago

When working with Persistent mapped buffers in C# and OpenTK, you end up needing to use unsafe operations and need to do something like:


WaitSyncStatus waitReturn = WaitSyncStatus.TimeoutExpired;
                    while (waitReturn != WaitSyncStatus.AlreadySignaled && waitReturn != WaitSyncStatus.ConditionSatisfied)
                    {
                        waitReturn = GL.ClientWaitSync(syncObj, ClientWaitSyncFlags.SyncFlushCommandsBit, 1);
                    }

                    //Write the data
                    unsafe
                    {
                        fixed (uint* SystemMemory = &data[0])
                        {
                            uint* VideoMemory = (uint*)mappedPtr.ToPointer();
                            for (int i = offset; i < ((length == -1) ? data.Length : length); i++)
                                VideoMemory[i] = SystemMemory[i - offset]; // simulate what GL.BufferData would do
                        }
                    }

                    // lock the buffer:
                    GL.DeleteSync(syncObj);
                    syncObj = GL.FenceSync(SyncCondition.SyncGpuCommandsComplete, WaitSyncFlags.None);

I'm thinking that it might be faster to invoke some native code here to read the data directly into the buffer for instance, by fread-ing to it. Would that perhaps be faster than the way I'm currently forced to do it? It feels like just looping over the array is the worst way to do it.

Advertisement
IIRC you can probably use Buffer.BlockCopy or Marshal.Copy.

I guess I should have researched this further. I ended up using Marshal.Copy for the version that works on a float[] but for the uint[] version (because for some reason .NET doesn't have an unsigned overload for Marshal.Copy) I can't figure out what to go with, I thought of using RtlMoveMemory via P/Invoke but that'd be Windows specific which is something I'd like to avoid, I did find Buffer.MemoryCopy which would be what I'm looking for but even though I'm using .NET 4.5 it doesn't appear to be available.

This topic is closed to new replies.

Advertisement