xamarin / xamarin-macios

.NET for iOS, Mac Catalyst, macOS, and tvOS provide open-source bindings of the Apple SDKs for use with .NET managed languages such as C#
Other
2.49k stars 515 forks source link

Not a good practice to access AudioQueueBuffer.AudioData by Marshal.ReadIntPtr #6410

Open zjli-2019 opened 5 years ago

zjli-2019 commented 5 years ago

I am working on iOS audio. After struggling with IntPtr-s, which might be a AudioQueueBuffer*, or pointing to raw samples, I finally managed to make things work.

But, I find below code seems not a good practice.

https://github.com/xamarin/xamarin-macios/blob/e45c3ba794e25c4ecb1c076678b733746ca184e4/src/AudioToolbox/AudioQueue.cs#L499

Steps to Reproduce

Check the source code of AudioQueue.FillAudioData(...).

public static void FillAudioData (IntPtr audioQueueBuffer, int offset, IntPtr source, int sourceOffset, nint size)
{
    // Here, location of field AudioData is almost *hard-coded*
    IntPtr target = Marshal.ReadIntPtr (audioQueueBuffer, IntPtr.Size);
    unsafe {
        byte *targetp = (byte *) target;
        byte *sourcep = (byte *) source;
        Runtime.memcpy (targetp + offset, sourcep + sourceOffset, size);
    }
}

Expected Behavior

  1. Use AudioQueueBuffer.AudioData;
  2. Use AudioQueueBuffer.CopyToAudioData(IntPtr source, int size).

Actual Behavior

The implementation seems not a good one.

Environment

N/A

Build Logs

N/A

Example Project (If Possible)

N/A

rolfbjarne commented 5 years ago

Our AudioQueue API is unfortunately not the best bindings we've created 😒. I had a quick look, and I saw many ways it can be improved, but the fact that we must be backwards compatible makes it much more complicated sometimes. I've filed #6411 so that hopefully one day we can fix this.