c# - DllImport or LoadLibrary for best performance -
i have external .dll file fast assembler code inside. best way call functions in .dll file best performance?
your dll might in python or c++, whatever , same follow.
this 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 @ 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); } }
Comments
Post a Comment