// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License.
using Microsoft.ML.OnnxRuntime.Tensors;
using System;
using System.Buffers;
using System.Collections.Generic;
namespace Microsoft.ML.OnnxRuntime
{
///
/// The class associates a name with an Object. Currently it supports Tensor
/// as possible objects. The name of the class is a misnomer, it does not hold any
/// Onnx values.
///
public class NamedOnnxValue
{
///
/// Managed Tensor, Dictionary or IList
///
protected Object _value;
///
/// Name of the instance, model input/output
///
protected string _name;
///
/// Constructs an instance of NamedOnnxValue and represents
/// a model input to an inference session. It also represents a modle output
/// when serves as a base for DisposablenamedOnnxvalue
///
/// input/output name
/// Object that may be a tensor, Dictionary, IList
protected NamedOnnxValue(string name, Object value)
{
_name = name;
_value = value;
}
///
/// This is a factory method that instantiates NamedOnnxValue
/// and associated name with an instance of a Tensor
///
///
/// name
/// Tensor
///
public static NamedOnnxValue CreateFromTensor(string name, Tensor value)
{
return new NamedOnnxValue(name, value);
}
///
/// Exposes the name of the of the model input/output
///
/// name string
public string Name { get { return _name; } set { _name = value; } }
///
/// Exposes the underlying managed object
///
/// object
public Object Value { get { return _value; } set { _value = value; } }
///
/// Try-get value as a Tensor<T>.
///
/// Type
/// Tensor object if contained value is a Tensor. Null otherwise
public Tensor AsTensor()
{
return _value as Tensor; // will return null if not castable
}
///
/// Try-get value as an Enumerable<T>.
///
/// Type
/// Enumerable object if contained value is a Enumerable. Null otherwise
public IEnumerable AsEnumerable()
{
var x = _value as IEnumerable;
return x;
}
///
/// Try-get value as an Dictionary<K,V>.
///
/// Key type
/// Value type
/// Dictionary object if contained value is a Dictionary. Null otherwise
public IDictionary AsDictionary()
{
return _value as IDictionary;
}
///
/// Pin the underlying memory and create an instance of OrtValue
/// based on the pinned managed memory. The caller is responsible for Disposing
/// both OrtValue and pinnedMemoryHandle
///
/// dispose after returned OrtValus is disposed
/// an instance of OrtValue. The lifespan of OrtValue must overlap pinnedMemoryHandle
internal virtual OrtValue ToOrtValue(out MemoryHandle? pinnedMemoryHandle)
{
return OrtValue.CreateFromTensorObject(_value, out pinnedMemoryHandle, out TensorElementType elementType);
}
// may expose different types of getters in future
}
}