c# - 非托管 DLL 的相对路径

标签 c# windows dll unmanaged

<分区>

Possible Duplicate:
Specify the search path for DllImport in .NET

我有一个非托管 DLL。为了清除,它是我想在我的 c# 代码中使用的 C++ dll。 问题是它是一个 Windows 应用程序,用户可以将它安装在他们选择的任何目录中。所以我不能用静态路径引用它,也找不到给出相对路径的方法。 这是我试过的代码:

 [DllImport("mydll.dll", CharSet = CharSet.Auto, SetLastError = true)]
  static extern bool SetDllDirectory(string lpPathName);

  public void SetDllDirectory(string lpPathName)
        {
            try
            {
                bool r = SetDllDirectory(lpPathName);
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }

        public void SetDirectoryPath()
        {
            try
            {
                DirectoryInfo directory = new DirectoryInfo(System.IO.Path.GetDirectoryName(System.Windows.Forms.Application.ExecutablePath));
                if (directory.Exists)
                    SetDllDirectory(directory.ToString() + "\\mydll.dll");

            }
            catch (Exception ex)
            {
                throw ex;
            }
        }

下面是我收到的错误。

Unable to find an entry point named 'SetDllDirectory' in DLL 'mydll.dll'.

这个问题可以复制

"C++ unmanaged DLL in c# "

"Relative Path to DLL in Platform Invoke Statement "

很抱歉,但我没有在这些引用资料中找到任何解决方案。

最佳答案

如果您尝试调用位于非标准位置的非托管库,您需要将此位置添加到 Windows 用于查找 dll 文件的 dll 搜索路径。

如果您的用户可以告诉程序c/c++库文件在哪里,您可以在他们选择时手动加载它。

public class UnsafeNativeMethods {
    [DllImport("kernel32.dll", SetLastError = true)]
    public static extern bool SetDllDirectory(string lpPathName);

    [DllImport("kernel32.dll", SetLastError = true)]
    public static extern int GetDllDirectory(int bufsize, StringBuilder buf);

    [DllImport("kernel32", CharSet = CharSet.Unicode, SetLastError = true)]
    public static extern IntPtr LoadLibrary(string librayName);

    [DllImport("mylibrary")]
    public static extern void InitMyLibrary();
}

您可以像这样以某种形式的预加载例程调用上面的内容:

public void LoadDllFile( string dllfolder, string libname ) {
    var currentpath = new StringBuilder(255);
    UnsafeNativeMethods.GetDllDirectory( currentpath.Length, currentpath );

    // use new path
    UnsafeNativeMethods.SetDllDirectory( dllfolder );

    UnsafeNativeMethods.LoadLibrary( libname );

    // restore old path
    UnsafeNativeMethods.SetDllDirectory( currentpath );
}

你可以这样调用它:

LoadDllFile( "c:\whatever", "mylibrary.dll" );

关于c# - 非托管 DLL 的相对路径,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9256901/

相关文章:

c# - 如何在 Visual Studio 2017 项目中启用 C# 7 的所有功能?

Windows批处理括号范围

c++ - Qt:如何创建 Windows DLL(导出函数)?

.net - 在没有管理员权限的情况下注册.Net COM DLL

c# - Convert.ToBoolean ("1") 在 C# 中抛出 System.Format 异常

C# 变量作用域 : 'x' cannot be declared in this scope because it would give a different meaning to 'x'

c++ - SSl 握手成功 C++

windows - 在 Windows 上的 Perl 中获取当前系统本地编码

c++ - 如何包含另一个目录中的 DLL

c# - session 关闭后加载子对象