Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the best way to concatenate two Windows Runtime Buffers?

I've written the following extension method to concatenate two IBuffer objects in a Windows Runtime application:

public static IBuffer Concat(this IBuffer buffer1, IBuffer buffer2)
{
    var capacity = (int) (buffer1.Length + buffer2.Length);
    var result = WindowsRuntimeBuffer.Create(capacity);
    buffer1.CopyTo(result);
    buffer2.CopyTo(0, result, buffer1.Length, buffer2.Length);
    return result;
}

Is this the most efficient way to handle this? Is there a better or easier way?

I've reviewed Best way to combine two or more byte arrays in C# but I don't think I should be converting to and from byte arrays.

like image 385
Matt Johnson-Pint Avatar asked Nov 03 '12 03:11

Matt Johnson-Pint


1 Answers

According to MSDN:

When you implement the IBuffer interface, you must implement the IBufferByteAccess interface, which is a COM interface for accessing the buffer directly. C++ callers use this interface to avoid making a copy of the buffer.

IBufferByteAccess has the following method:

HRESULT Buffer(
  [out]  byte **value
);

If you write in C++, you may use this interface to facilitate implementing data copying efficiently. However, class System.Runtime.InteropServices.WindowsRuntime.WindowsRuntimeBufferExtensions, which you used in your method, is implemented in native code as well, thus it almost certanly takes advantage of the IBufferByteAccess interface. Calling method WindowsRuntimeBufferExtensions.CopyTo from managed code should be as fast as implementing its equivalent in native code and calling that implementation (unless a customized implementation would do less validation).

like image 52
Roman Boiko Avatar answered Sep 18 '22 08:09

Roman Boiko