Search code examples
c#c++pinvokedllimport

DllImport params on attribute


Can I instead of the name library, substitute parameter?

for example:

Now

[DllImport("First.dll")]
public static extern bool Info([MarshalAs(UnmanagedType.BStr)] ref string result);

Want

private static string dllName = "Second.dll"

[DllImport(dllName)]
public static extern bool Info([MarshalAs(UnmanagedType.BStr)] ref string result);

Solution

  • No. You can use a const but not a variable.

    If you have a good reason (i.e. not simply avoiding repeated declarations) you can do it dynamically by p/invoking LoadLibrary -> GetProcAddress then calling the export via UnmanagedFunctionPointer.