NativeApiStatus.shared.cs 1.37 KB
Newer Older
gaoqiong's avatar
gaoqiong committed
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License.

using System;

namespace Microsoft.ML.OnnxRuntime
{
    class NativeApiStatus
    {
        private static string GetErrorMessage(IntPtr /*(ONNXStatus*)*/status)
        {
            // nativeString belongs to status, no need for separate release
            IntPtr nativeString = NativeMethods.OrtGetErrorMessage(status);
            return NativeOnnxValueHelper.StringFromNativeUtf8(nativeString);
        }

        /// <summary>
        /// Checks the native Status if the errocode is OK/Success. Otherwise constructs an appropriate exception and throws.
        /// Releases the native status object, as needed.
        /// </summary>
        /// <param name="nativeStatus"></param>
        /// <throws></throws>
        public static void VerifySuccess(IntPtr nativeStatus)
        {
            if (nativeStatus != IntPtr.Zero)
            {
                try
                {
                    ErrorCode statusCode = NativeMethods.OrtGetErrorCode(nativeStatus);
                    string errorMessage = GetErrorMessage(nativeStatus);
                    throw new OnnxRuntimeException(statusCode, errorMessage);
                }
                finally
                {
                    NativeMethods.OrtReleaseStatus(nativeStatus);
                }
            }
        }
    }
}