1

In C#, I can do something like:

public partial class Form1 : Form
{
    [DllImport("veie_dll.dll", EntryPoint = "my_multiply"]
    public static extern int my_multiply(int x, int y);

But when I try to use a variable for the dll name (so I can use it in error messages) like this:

public partial class Form1 : Form
{
    string dllName = "veie_dll.dll";

    [DllImport(dllName, EntryPoint = "my_multiply"]
    public static extern int my_multiply(int x, int y);

I get an error: CS0120 An object reference is required for the non-static field, method, or property 'Form1.dllName'

Any suggestions on how to do this properly?

  • i don't think you can. but what do you want to use it for? – Franz Gleichmann May 11 '20 at 16:49
  • 3
    What happens if you follow the compiler's hint and stick a `static` and/or `const` in front of the string? – 500 - Internal Server Error May 11 '20 at 16:51
  • What do you want to achieve with "use *variable* for DLL name"? (Obviously it is something to do with file name as path is easy - https://stackoverflow.com/questions/8836093/how-can-i-specify-a-dllimport-path-at-runtime) – Alexei Levenkov May 11 '20 at 16:57
  • What I tried to accomplish: That dll name is used at quite a few places (different function imports, error message when something goes wrong with the dll) and I don't want to have to modify all those literals when my dll name changes. I just want to change it one place only. Maybe I shouldn't have said 'variable', but constant. Which would have also hinted at the solution given by Prakash below: just add 'const' to dllName. That fixed it! Which is a bit odd since the DLLImport prototype doesn't show a 'const string', just a 'string'). But hey, it works ... ;-) – Paul Claessen May 11 '20 at 17:20

1 Answers1

1

I would say if you want use string variable then it should be const variable then only it works, there is no other option I could see.

public const string dllName = "veie_dll.dll";

Prakash
  • 813
  • 1
  • 8
  • 20