DllImport or LoadLibrary for best performance

后端 未结 4 1577
温柔的废话
温柔的废话 2020-12-30 12:09

I have external .DLL file with fast assembler code inside. What is the best way to call functions in this .DLL file to get best performance?

4条回答
  •  说谎
    说谎 (楼主)
    2020-12-30 12:40

    Your DLL might be in python or c++, whatever , do the same as follow.

    This is your DLL file in C++.

    header:

    extern "C" __declspec(dllexport) int MultiplyByTen(int numberToMultiply);
    

    Source code file

    #include "DynamicDLLToCall.h"
    
    int MultiplyByTen(int numberToMultiply)
    {
        int returnValue = numberToMultiply * 10;
        return returnValue;
    } 
    

    Take a look at the following C# code:

    static class NativeMethods
    {
        [DllImport("kernel32.dll")]
        public static extern IntPtr LoadLibrary(string dllToLoad);
    
        [DllImport("kernel32.dll")]
        public static extern IntPtr GetProcAddress(IntPtr hModule, string procedureName);
    
        [DllImport("kernel32.dll")]
        public static extern bool FreeLibrary(IntPtr hModule);
    }
    
    class Program
    {
        [UnmanagedFunctionPointer(CallingConvention.Cdecl)]
        private delegate int MultiplyByTen(int numberToMultiply);
    
        static void Main(string[] args)
        {
                IntPtr pDll = NativeMethods.LoadLibrary(@"PathToYourDll.DLL");
                //oh dear, error handling here
                //if (pDll == IntPtr.Zero)
    
                IntPtr pAddressOfFunctionToCall = NativeMethods.GetProcAddress(pDll, "MultiplyByTen");
                //oh dear, error handling here
                //if(pAddressOfFunctionToCall == IntPtr.Zero)
    
                MultiplyByTen multiplyByTen = (MultiplyByTen)Marshal.GetDelegateForFunctionPointer(
                                                                                        pAddressOfFunctionToCall,
                                                                                        typeof(MultiplyByTen));
    
                int theResult = multiplyByTen(10);
    
                bool result = NativeMethods.FreeLibrary(pDll);
                //remaining code here
    
                Console.WriteLine(theResult);
        }
    } 
    

提交回复
热议问题