C# 属性上的DllImport参数
我可以用替换参数代替名称库吗 例如: 现在C# 属性上的DllImport参数,c#,c++,pinvoke,dllimport,C#,C++,Pinvoke,Dllimport,我可以用替换参数代替名称库吗 例如: 现在 [DllImport("First.dll")] public static extern bool Info([MarshalAs(UnmanagedType.BStr)] ref string result); 想要 private static string dllName = "Second.dll" [DllImport(dllName)] public static extern bool Info([MarshalAs(Unmanag
[DllImport("First.dll")]
public static extern bool Info([MarshalAs(UnmanagedType.BStr)] ref string result);
想要
private static string dllName = "Second.dll"
[DllImport(dllName)]
public static extern bool Info([MarshalAs(UnmanagedType.BStr)] ref string result);
不可以。可以使用常量,但不能使用变量
如果您有充分的理由(即不只是避免重复声明)您可以通过p/调用
LoadLibrary
->GetProcAddress
然后通过UnmanagedFunctionPointer
调用导出,这与其说是关于DllImport
和p/调用的问题,不如说是关于C#attributes语言特性的问题。你完全可以用属性知识来回答这个问题。关键知识是属性的参数必须是常数。因为这些参数是在编译时计算的,所以它们不能是变量
因此,答案是问题中的代码无法编译,因为您试图使用变量作为属性的参数。您可以将参数更改为常量,如下所示:
private const string dllName = "Second.dll";
[DllImport(dllName)]
....
你测试过了吗?你可以试着在几秒钟内找到答案。