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.
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).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With