From 5326e35571bfa29b1076a9616a1bef10fc7ee3fc Mon Sep 17 00:00:00 2001 From: dahall Date: Fri, 8 Oct 2021 09:20:54 -0600 Subject: [PATCH] Added GetProcAddress methods to SafeHINSTANCE --- PInvoke/Kernel32/LibLoaderApi.cs | 38 ++++++++++++++++++++++++++++++++++++++ 1 file changed, 38 insertions(+) diff --git a/PInvoke/Kernel32/LibLoaderApi.cs b/PInvoke/Kernel32/LibLoaderApi.cs index 19ea0d88..877c9efc 100644 --- a/PInvoke/Kernel32/LibLoaderApi.cs +++ b/PInvoke/Kernel32/LibLoaderApi.cs @@ -2063,6 +2063,44 @@ namespace Vanara.PInvoke /// The result of the conversion. public static implicit operator HINSTANCE(SafeHINSTANCE h) => h.handle; + /// Retrieves the address of an exported function or variable from the specified dynamic-link library (DLL). + /// The function or variable name. + /// + /// If the function succeeds, the return value is the address of the exported function or variable. + /// If the function fails, an exception with the error is thrown. + /// + public IntPtr GetProcAddress(string procName) => Win32Error.ThrowLastErrorIfNull(Kernel32.GetProcAddress(handle, procName)); + + /// Retrieves the address of an exported function or variable from the specified dynamic-link library (DLL). + /// The function's ordinal value. + /// + /// If the function succeeds, the return value is the address of the exported function or variable. + /// If the function fails, an exception with the error is thrown. + /// + public IntPtr GetProcAddress(int ordinal) => GetProcAddress($"#{ordinal}"); + + /// Retrieves a delegate for an exported function or variable from the specified dynamic-link library (DLL). + /// The delegate type to which to convert that function pointer. + /// The function or variable name. + /// + /// If the function succeeds, the return value is the exported function or variable's delegate. + /// If the function fails, an exception with the error is thrown. + /// + public T GetProcAddress(string procName) where T : Delegate + { + var ptr = Win32Error.ThrowLastErrorIfNull(Kernel32.GetProcAddress(handle, procName)); + return (T)Marshal.GetDelegateForFunctionPointer(ptr, typeof(T)); + } + + /// Retrieves a delegate for an exported function or variable from the specified dynamic-link library (DLL). + /// The delegate type to which to convert that function pointer. + /// The function's ordinal value. + /// + /// If the function succeeds, the return value is the exported function or variable's delegate. + /// If the function fails, an exception with the error is thrown. + /// + public T GetProcAddress(int ordinal) where T : Delegate => GetProcAddress($"#{ordinal}"); + /// protected override bool InternalReleaseHandle() => FreeLibrary(this); }