Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/csharp/330.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/6/cplusplus/157.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C# 属性上的DllImport参数_C#_C++_Pinvoke_Dllimport - Fatal编程技术网

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)]
....

你测试过了吗?你可以试着在几秒钟内找到答案。