c# - Dynamically generate code for DllImport depending on application version -
i write .net-extension can loaded different versions of unmanaged application.
below imported some_func_v01
, some_func_v02
, , some_func_v03
functions:
[dllimport("some_library_v1.0.dll", callingconvention = callingconvention.cdecl, charset = charset.unicode, entrypoint = "func_name")] extern static private void some_func_v01(string msg); [dllimport("some_library_v2.0.dll", callingconvention = callingconvention.cdecl, charset = charset.unicode, entrypoint = "func_name")] extern static private void some_func_v02(string msg); [dllimport("some_library_v3.0.dll", callingconvention = callingconvention.cdecl, charset = charset.unicode, entrypoint = "func_name")] extern static private void some_func_v03(string msg); ... public void some_func(string msg) { switch (application.version.major) { case 1: some_func_v01(msg); break; case 2: some_func_v02(msg); break; case 3: some_func_v03(msg); break; } }
the some_library
library part of target application , has same version application.
the problem edit code of extension when new versions of application appear. dynamically generate code depending of application version. example, application version 1:
[dllimport("some_library_v1.0.dll", callingconvention = callingconvention.cdecl, charset = charset.unicode, entrypoint = "func_name")] extern static private void some_func(string msg);
i can through powershell hosting using, maybe more simple way exists... wouldn't want create powershell hosting carry out task.
is exist simple way it?
i think best solution load dlls dynamically.
use winapi loadlibrary , getprocaddress address of function. use marshal.getdelegateforfunctionpointer .net delegate.
example:
//skipping winapi native definitions //you need define delegate type: [unmanagedfunctionpointer(callingconvention.stdcall, charset = charset.unicode, setlasterror = true)] delegate void myfunctype(string msg); //how delegate object: var library = loadlibrary(librarynamechosenatruntime); var funcptr = getprocaddress(library, funcname); var func = marshal.getdelegateforfunctionpointer<myfunctype>(funcptr); // can use func delegate // can store delegate object somewhere , reuse. func("msg");
Comments
Post a Comment