将环境变量分配给结构中的 const 字符串


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)]抛出以下错误。

属性参数

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


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

public const string dll = "PathToBeReferenced";

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

不,您所要求的是使用此特定机制无法实现的。需要在编译时计算属性构造函数参数。程序的环境变量在运行时之前不存在。

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

有关详细信息,请参阅如何在运行时指定 [DllImport] 路径?

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

最新更新