DllImport或LoadLibrary可获得最佳性能
问题描述:
我有外部.DLL文件,其中带有快速汇编代码。调用此.DLL文件中的函数以获得最佳性能的最佳方法是什么?
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?
答
您的DLL可能位于python或c ++,无论做什么,都执行以下操作。
Your DLL might be in python or c++, whatever , do the same as follow.
这是C ++中的DLL文件。
This is your DLL file in C++.
标题:
extern "C" __declspec(dllexport) int MultiplyByTen(int numberToMultiply);
源代码文件
#include "DynamicDLLToCall.h"
int MultiplyByTen(int numberToMultiply)
{
int returnValue = numberToMultiply * 10;
return returnValue;
}
看看下面的C#代码:
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);
}
}