相关疑难解决方法(0)

如何在运行时指定[DllImport]路径?

事实上,我得到了一个C++(工作)DLL,我想导入我的C#项目来调用它的函数.

当我指定DLL的完整路径时,它确实有效,如下所示:

string str = "C:\\Users\\userName\\AppData\\Local\\myLibFolder\\myDLL.dll";
[DllImport(str, CallingConvention = CallingConvention.Cdecl)]
public static extern int DLLFunction(int Number1, int Number2);
Run Code Online (Sandbox Code Playgroud)

问题是它将是一个可安装的项目,因此用户的文件夹将不同(例如:皮埃尔,保罗,杰克,妈妈,爸爸......),这取决于计算机/会话的运行情况.

所以我希望我的代码更通用,如下所示:

/* 
goes right to the temp folder of the user 
    "C:\\Users\\userName\\AppData\\Local\\temp"
then go to parent folder
    "C:\\Users\\userName\\AppData\\Local"
and finally go to the DLL's folder
    "C:\\Users\\userName\\AppData\\Local\\temp\\myLibFolder"
*/

string str = Path.GetTempPath() + "..\\myLibFolder\\myDLL.dll"; 
[DllImport(str, CallingConvention = CallingConvention.Cdecl)]
public static extern int DLLFunction(int Number1, int Number2);
Run Code Online (Sandbox Code Playgroud)

最重要的是"DllImport"需要DLL目录的"const string"参数.

所以我的问题是::在这种情况下可以做些什么?

c# c++ dll constants dllimport

129
推荐指数
5
解决办法
13万
查看次数

在.NET中指定DllImport的搜索路径

有没有办法为使用DllImport导入的给定程序集指定要搜索的路径?

[DllImport("MyDll.dll")]
static extern void Func();
Run Code Online (Sandbox Code Playgroud)

这将在app dir和PATH环境变量中搜索dll.但有时dll会放在其他地方.可以在app.config或清单文件中指定此信息以避免动态加载和动态调用吗?

.net dllimport

53
推荐指数
3
解决办法
3万
查看次数

标签 统计

dllimport ×2

.net ×1

c# ×1

c++ ×1

constants ×1

dll ×1