【问题标题】:Assigning environment variables to a const string in a struct [duplicate]将环境变量分配给结构中的常量字符串[重复]
【发布时间】:2019-08-08 13:10:14
【问题描述】:
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 正在引用要存储在dll 变量中的路径。

dll分配代码抛出以下错误信息

分配给 DLLProjCore2 的表达式必须是常量。

[DllImport(DLLProjCore2.dll)] 抛出以下错误。

属性参数必须是属性参数类型的常量表达式、typeof表达式或数组创建表达式


一旦硬编码要分配给dll 的值,项目就会正确编译。

public const string dll = "PathToBeReferenced";

有没有办法动态访问[DllImport(DLLProjCore2.dll)] 中的dll 变量值? (没有硬编码,发布解决方案后需要从外部引用)

【问题讨论】:

  • 您可以使用静态只读字段而不是 const。
  • @Joe 不,那也行不通。这会将错误转移到[DllImport(DLLProjCore2.dll)] 行,因为需要在编译时评估参数。
  • @cdhowie 感谢您的快速回复。有什么建议可以完成这项任务吗?
  • @HarshaW 查看 Dmitry 链接的问题。

标签: c# struct constants dllimport


【解决方案1】:

不,使用此特定机制无法实现您的要求。属性构造函数参数需要在编译时进行评估。程序的环境变量在运行时才存在。

【讨论】:

    【解决方案2】:

    您可以尝试使用相对路径(不是绝对路径)并更改Environment.CurrentDirectory以加载要加载的dll:

    详情请见How can I specify a [DllImport] path at runtime?

    // 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;
      }
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2021-05-12
      • 1970-01-01
      • 1970-01-01
      • 2021-03-19
      • 1970-01-01
      • 2014-08-20
      • 2020-10-08
      相关资源
      最近更新 更多