实际上,我得到了一个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、妈妈、爸爸……)取决于运行它的计算机/会话。
所以我希望我的代码更通用一些,就像这样:
/*
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“需要为DLL目录提供一个"const string”参数。
所以我的问题是:在这种情况下可以做些什么?
发布于 2012-01-12 22:46:24
比Ran建议使用GetProcAddress
更好的是,只需在调用任何DllImport
函数之前调用LoadLibrary
(只有一个文件名,没有路径),它们就会自动使用加载的模块。
我已经使用此方法在运行时选择是加载32位还是64位本机DLL,而不必修改一堆P/Invoke-d函数。将加载代码放在具有导入函数的类型的静态构造函数中,一切都会正常工作。
发布于 2017-01-19 21:36:23
如果您知道C++库在运行时所在的目录,就会很简单。我可以在你的问题陈述中看到这一点。名为myDll.dll
的程序集将出现在当前用户的临时文件夹内的myLibFolder
目录中。
string str = Path.GetTempPath() + "..\\myLibFolder\\myDLL.dll";
您可以使用常量字符串继续使用DllImport
语句,如下所示:
[DllImport("myDLL.dll", CallingConvention = CallingConvention.Cdecl)]
public static extern int DLLFunction(int Number1, int Number2);
在C#代码中调用DLLFunction
函数(存在于C++库中)之前,添加以下代码行:
string assemblyProbeDirectory = Path.GetTempPath() + "..\\myLibFolder\\myDLL.dll";
Directory.SetCurrentDirectory(assemblyProbeDirectory);
这将指示.NET CLR在您在运行时获得的目录路径中查找非托管C++库。调用Directory.SetCurrentDirectory
将应用程序的当前工作目录设置为指定的目录。如果您的路径存在于由assemblyProbeDirectory
myDLL.dll
表示的路径中,那么它将被加载。然后,您可以通过p/invoke调用所需的函数。
发布于 2019-05-16 11:42:03
在配置文件中设置dll路径
<add key="dllPath" value="C:\Users\UserName\YourApp\myLibFolder\myDLL.dll" />
在应用程序中调用dll之前,请执行以下操作
string dllPath= ConfigurationManager.AppSettings["dllPath"];
string appDirectory = Path.GetDirectoryName(dllPath);
Directory.SetCurrentDirectory(appDirectory);
然后调用dll,您可以像下面这样使用
[DllImport("myDLL.dll", CallingConvention = CallingConvention.Cdecl)]
public static extern int DLLFunction(int Number1, int Number2);
https://stackoverflow.com/questions/8836093
复制相似问题