// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. // SPDX-License-Identifier: Apache-2.0 // Standard Library using System; namespace AWS.GameKit.Runtime.Utils { /// /// Class to help with calling exported DLL functions. /// public static class DllLoader { /// /// Tries to call imported DLL method. Logs Dll Exception if unsuccessful. /// /// The imported method to call. /// Name of the dll the method is in. public static void TryDll(Action importedMethod, string dllName) { try { importedMethod(); } catch (Exception e) { LogDllException(e, dllName); } } /// /// Tries to call imported DLL method. Logs Dll Exception if unsuccessful. /// /// The imported method to call. /// Name of the dll the method is in. public static T TryDll(Func importedMethod, string dllName, T returnOnError) { try { return importedMethod(); } catch (Exception e) { LogDllException(e, dllName); return returnOnError; } } /// /// Tries to call imported DLL method. Logs Dll Exception if unsuccessful. /// /// The imported method to call. /// Name of the dll the method is in. /// The object this method is called on. public static void TryDll(object dispatchReceiver, Action importedMethod, string dllName) { Marshaller.Dispatch(dispatchReceiver, (IntPtr handle) => { try { importedMethod(handle); } catch (Exception e) { LogDllException(e, dllName); } }); } /// /// Tries to call imported DLL method. Logs Dll Exception if unsuccessful. /// /// The imported method to call. /// Name of the dll the method is in. /// The object this method is called on. public static T TryDll(object dispatchReceiver, Func importedMethod, string dllName, T returnOnError) { return Marshaller.Dispatch(dispatchReceiver, (IntPtr handle) => { try { return importedMethod(handle); } catch (Exception e) { LogDllException(e, dllName); return returnOnError; } }); } private static void LogDllException(Exception e, string dllName) { if (e is DllNotFoundException || e is EntryPointNotFoundException) { Logging.LogException($"{dllName} DLL not linked", e); } else { Logging.LogException("Unable to make call to DLL imported method, {}, ", e); } } } }