从 C# 获取指向 Windows.AI.MachineLearning.TensorFloat 中数据的指针

Get pointer to data in Windows.AI.MachineLearning.TensorFloat from C#

我想获得指向我的 C# .NET Core 5.0 应用程序中 TensorFloat 背后的数据的指针。我首先声明 IMemoryBufferByteAccess:

[ComImport]
[Guid("5b0d3235-4dba-4d44-865e-8f1d0e4fd04d")]
[InterfaceType(ComInterfaceType.InterfaceIsIUnknown)]
unsafe interface IMemoryBufferByteAccess
{
    void GetBuffer(out byte* buffer, out uint capacity);
}

那么,经过推理,我尝试如下使用:

var outputTensor = (TensorFloat)session.Evaluate(binding, "0").Outputs["myAwesomeOutput:0"];
using var outputReference = outputTensor.CreateReference();
((IMemoryBufferByteAccess)outputReference).GetBuffer(out var onnxOutput, out var onnxCapacity);

这导致 System.InvalidCastException: 'Invalid cast from 'WinRT.IInspectable' to 'IMemoryBufferByteAccess'.',这是令人惊讶的,因为对于 Windows.Foundation.IMemoryBufferReference 的 Windows.Media and Windows.Graphics. The documentation 甚至状态的完全相同的方法:

The same object identity must also implement the COM interface IMemoryBufferByteAccess. A client retrieves the IMemoryBufferByteAccess interface pointer via a QueryInterface from the IMemoryBufferReference object.

我错过了什么?

我设法让它工作了。首先我必须导入一个扩展方法:

using WinRT;

然后使用As(...)扩展方法转换为IMemoryBufferByteAccess获取指针:

outputReference.As<IMemoryBufferByteAccess>().GetBuffer(out var onnxOutput, out var onnxCapacity);