DllImport Attribute Issue

G

Guest

Hello,

I am getting the following error:

"An attribute argument must be a constant expression, typeof expression or
array creation expression"

with this line of code on my GetDLLName() that gets the DllName parameter
for the DllImport:

[DllImport(GetDLLName(), EntryPoint = "Logon", CallingConvention =
CallingConvention.StdCall, CharSet = CharSet.Auto, SetLastError = true)]
public static extern int Logon(ref LOGON_INFO rvLogon);

Here is the GetDLLName() function:

private static string GetDLLName()
{
string DLLName = string.Empty;

#if (DEBUG)
//Constant to store the value for the WIN32 DLL
supplied by Teledirect
//Assumes the DLL will reside in the
C:\WINNT\System32 directory
DLLName = "(''" +
@Environment.SystemDirectory.ToString() + @"\myDLL.dll" + "'')";
#else
//Constant to store the value for the WIN32 DLL
supplied by Teledirect
//Assumes the DLL will reside in the
C:\WINNT\System32 directory
DLLName = "(''" +
@Environment.SystemDirectory.ToString() + @"\myDLL.dll" + "'')";
#endif

return DLLName.ToString();
}

I have not used the DllImport Attribute before, but what I can see it takes
a String value for the DllName, and a set of NamedParameters that are
optional.

Can anyone tell me what I am doing wrong and how to correct it?

Thanks,
 
J

Jon Skeet [C# MVP]

I have not used the DllImport Attribute before, but what I can see it takes
a String value for the DllName, and a set of NamedParameters that are
optional.

Can anyone tell me what I am doing wrong and how to correct it?

As the compiler error says, the value of an attribute argument (the
DLL name in your case) must be a constant. That rules out using the
result of a method call.

If your method just chose between two constants based on DEBUG, you
could just have two constants - but it's using the system directory,
which is dynamic.

(To understand why this all needs to be constant - the value gets
compiled directly into the assembly as a constant - there's no runtime
initialization.)

Jon
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top