0
namespace DLLProj
{
   struct DLLProjCore2
     {
       public const string dll = Environment.GetEnvironmentVariable("DLLProj_HOME", EnvironmentVariableTarget.Machine).ToString();
     }

    [DllImport(DLLProjCore2.dll)]
    public static extern void met1_method1(string prefix, string version);

    [DllImport(DLLProjCore2.dll, CharSet = CharSet.Ansi)]
    public static extern long met1_method2(IntPtr error, string licenseFile);

}

DLLProjectCore2 is referencing the path to be stored in dll variable.

dll assigning code throws the below error message

The expression is being assigned to DLLProjCore2 must be a constant.

[DllImport(DLLProjCore2.dll)] throw the below error.

An attribute argument must be a constant expression, typeof expression or array creation expression of an attribute parameter type


Once hardcode the value to be assigned to the dll, the project compiles properly.

public const string dll = "PathToBeReferenced";

Is there a way to access the dll variable value in [DllImport(DLLProjCore2.dll)] dynamically? (Without hardcoding, need to refer it from an outside location after publishing the solution)

Harsha W
  • 3,162
  • 5
  • 43
  • 77

2 Answers2

1

No, what you are asking is not possible using this specific mechanism. Attribute constructor arguments need to be evaluated at compile time. Environment variables of your program don't exist until runtime.

cdhowie
  • 158,093
  • 24
  • 286
  • 300
0

You can try using relative path (not absolute one) and change Environment.CurrentDirectory for the dll to be loaded:

see How can I specify a [DllImport] path at runtime? for details

// readonly (instead of const) allows to get value at runtime
public static readonly string dll =       Environment
  .GetEnvironmentVariable("DLLProj_HOME", EnvironmentVariableTarget.Machine)
  .ToString();

// Relative Path
//TODO: put the right dll name here 
[DllImport("DLLProjCore2.dll", EntryPoint = "met1_method1")]
private static extern void Core_met1_method1(string prefix, string version);

public static void met1_method1(string prefix, string version) {
  string savedPath = Environment.CurrentDirectory;

  try {
    // We set current directory
    Environment.CurrentDirectory = Path.GetDirectoryName(dll);
    // And so we can load library by its relative path 
    met1_method1(prefix, version);
  }
  finally {
    Environment.CurrentDirectory = savedPath;
  }
}
Dmitry Bychenko
  • 180,369
  • 20
  • 160
  • 215