private static void Benchmark(MaxDelegate myMethod, int[] data) { Stopwatch sw = Stopwatch.StartNew(); var result = myMethod.DynamicInvoke(data); sw.Stop(); Console.WriteLine(); Console.WriteLine("\tTime taken: {0}ms, result: {1}", sw.Elapsed.TotalMilliseconds, result); }
static void Main(string[] args) { bool isLoaded = false; const string moduleName = "CppDynamicLinkLibrary"; // Check whether or not the module is loaded. isLoaded = IsModuleLoaded(moduleName); Console.WriteLine("Module \"{0}\" is {1}loaded", moduleName, isLoaded ? "" : "not "); // Load the DLL module. Console.WriteLine("Load the library"); using (UnmanagedLibrary lib = new UnmanagedLibrary(moduleName)) { // Check whether or not the module is loaded. isLoaded = IsModuleLoaded(moduleName); Console.WriteLine("Module \"{0}\" is {1}loaded", moduleName, isLoaded ? "" : "not "); // // Access the global data exported from the module. // // The solution does not allow you to access the global data // exported from a DLL module. // // Call the functions exported from the module. // string str = "HelloWorld"; int length; // Call int /*__cdecl*/ GetStringLength1(PWSTR pszString); GetStringLength1Delegate GetStringLength1 = lib.GetUnmanagedFunction <GetStringLength1Delegate>( "GetStringLength1"); if (GetStringLength1 == null) { throw new EntryPointNotFoundException( "Unable to find an entry point named 'GetStringLength1'"); } length = GetStringLength1(str); Console.WriteLine("GetStringLength1(\"{0}\") => {1}", str, length); // Call int __stdcall GetStringLength2(PWSTR pszString); GetStringLength2Delegate GetStringLength2 = lib.GetUnmanagedFunction <GetStringLength2Delegate>( "_GetStringLength2@4"); if (GetStringLength2 == null) { throw new EntryPointNotFoundException( "Unable to find an entry point named 'GetStringLength2'"); } length = GetStringLength2(str); Console.WriteLine("GetStringLength2(\"{0}\") => {1}", str, length); // // Call the callback functions exported from the module. // CompareCallback cmpFunc = new CompareCallback(CompareInts); MaxDelegate Max = lib.GetUnmanagedFunction <MaxDelegate>("Max"); if (Max == null) { throw new EntryPointNotFoundException( "Unable to find an entry point named 'Max'"); } int max = Max(2, 3, cmpFunc); Console.WriteLine("Function: Max(2, 3) => {0}", max); // // Use the class exported from a module. // // The solution does not allow you to use the class exported // from the DLL. // Attempt to free the library on exit. Console.WriteLine("Unload the dynamically-loaded DLL"); } // The DLL module should be unloaded here. // Check whether or not the module is loaded. isLoaded = IsModuleLoaded(moduleName); Console.WriteLine("Module \"{0}\" is {1}loaded", moduleName, isLoaded ? "" : "not "); }