C# 将环境变量分配给结构中的常量字符串
DLLProjectCore2正在引用要存储在dll变量中的路径 dll分配代码抛出以下错误消息 正在分配给DLLProjCore2的表达式必须是常量 [DllImportDLLProjCore2.dll]抛出以下错误 属性参数必须是常量表达式、typeof表达式或属性参数类型的数组创建表达式 将要分配给dll的值硬编码后,项目将正确编译C# 将环境变量分配给结构中的常量字符串,c#,struct,constants,dllimport,C#,Struct,Constants,Dllimport,DLLProjectCore2正在引用要存储在dll变量中的路径 dll分配代码抛出以下错误消息 正在分配给DLLProjCore2的表达式必须是常量 [DllImportDLLProjCore2.dll]抛出以下错误 属性参数必须是常量表达式、typeof表达式或属性参数类型的数组创建表达式 将要分配给dll的值硬编码后,项目将正确编译 namespace DLLProj { struct DLLProjCore2 { public const string dl
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);
}
是否有方法动态访问[DllImportDLLProjCore2.dll]中的dll变量值?如果没有硬编码,则需要在发布解决方案后从外部位置引用它否,使用此特定机制不可能实现您的要求。属性构造函数参数需要在编译时进行计算。程序的环境变量在运行时之前不存在。您可以尝试使用相对路径而不是绝对路径,并更改要加载的dll的Environment.CurrentDirectory: 有关详细信息,请参阅
public const string dll = "PathToBeReferenced";
您可以使用静态只读字段而不是常量。@Joe不,这也不行。这会将错误移到[DllImportDLLProjCore2.dll]行,因为需要在编译时对参数进行计算。@cdhowie感谢您的快速回复。对完成这项任务有什么建议吗?@HarshaW看到了Dmitry链接的问题。
// 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;
}
}