实际上,我有一个可以工作的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);
问题在于这将是一个可安装的项目,因此用户的文件夹将根据运行它的计算机/会话而不同(例如:pierre、paul、jack、mum、dad等)。
所以我希望我的代码能更加通用,像这样:
/*
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);
"DllImport"需要一个"const string"参数来指定DLL的目录,这是非常重要的。
所以我的问题是:在这种情况下应该怎么做?
Directory.SetCurrentDirectory(DLLsFolder)
,DLL是按需加载的,所以在实例化使用引用DLL的对象之前,请调用“SetCurrentDirectory”。在使用dllimport加载后,当进程结束(或任何AppDomain完成)时,dll将被卸载。 - antonio