Set DllImport attribute dynamically

I am using an external unmanaged dll using PInvoke and the DllImport attribute. eg.

[DllImport("mcs_apiD.dll", CharSet = CharSet.Auto)] private static extern byte start_api(byte pid, byte stat, byte dbg, byte ka); 

I am wondering if it is possible to somehow modify the data of the dll file (mcs_apiD.dll in this example) in some way, if, for example, I wanted to build against a different version of the dll

+6
c # pinvoke
May 12 '10 at 10:44
source share
2 answers

Yes, it is possible, you will need to complete part of the task that the P / Invoke marshaller does. Download the DLL and search for the entry point of the exported function. Start by declaring a delegate whose signature matches the exported function:

  private delegate byte start_api(byte pid, byte stat, byte dbg, byte ka); 

Then use this code:

  using System.ComponentModel; using System.Runtime.InteropServices; ... static IntPtr dllHandle; ... if (dllHandle == IntPtr.Zero) { dllHandle = LoadLibrary("mcs_apiD.dll"); if (dllHandle == IntPtr.Zero) throw new Win32Exception(); } IntPtr addr = GetProcAddress(dllHandle, "_start_api@16"); if (addr == IntPtr.Zero) throw new Win32Exception(); var func = (start_api)Marshal.GetDelegateForFunctionPointer(addr, typeof(start_api)); var retval = func(1, 2, 3, 4); ... [DllImport("kernel32.dll", CharSet = CharSet.Auto, SetLastError = true)] private static extern IntPtr LoadLibrary(string name); [DllImport("kernel32.dll", CharSet = CharSet.Ansi, SetLastError = true)] private static extern IntPtr GetProcAddress(IntPtr hModule, string name); 

Many ways to do it wrong. Note that you must use the actual exported name from the DLL, you no longer get help from Marshall P / Invoke to help decorate the names. Use dumpbin.exe / exports in the DLL if you do not know what the export name looks like.

+5
May 12 '10 at 12:58 a.m.
source share

you cannot change the dll name, but you can change the path to the library you are loading (for example, reading it from the registry or configuration file) and load it manually using the LoadLibrary kernel32 function: see my answer there .

+2
May 12 '10 at 10:49
source share



All Articles