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
.
Question
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
.
OTHER TIPS
This is not so much a question about DllImport
and p/invoke as one about the C# attributes language feature. You can answer the question purely with knowledge of attributes. And the key knowledge is that the parameters to attributes must be constant. Since these parameters are evaluated at compile time, they cannot be variables.
So the answer is that the code in your question does not compile because you are trying to use a variable as a parameter to an attribute. You can change the parameter to be a constant, like this:
private const string dllName = "Second.dll";
[DllImport(dllName)]
....