LoadLibrary函数在Vista和XP中返回null

时间:2012-04-03 09:16:17

标签: c# .net

我的应用程序在Win 7 x86和x64测试环境中正常工作,但在Vista和XP上却没有。

这是示例代码:

internal static class NativeMethods
{

    [DllImport("kernel32.dll", CharSet = CharSet.Unicode, SetLastError = true)]
    [return: MarshalAs(UnmanagedType.Bool)]
    internal static extern bool SetDllDirectory(string lpPathName);

    [DllImport("kernel32", SetLastError = true)]
    internal static extern IntPtr LoadLibrary(string lpFileName);
}
....

string path = Path.Combine(Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location), "Native");
path = Path.Combine(path, string.Format("x{0}", IntPtr.Size*8));

NativeMethods.SetDllDirectory(path);
IntPtr ptr2 = NativeMethods.LoadLibrary("SQLite.Interop.dll");

在Vista或XP中IntPtr == null无论x86还是x64。

.net Framework 2下的解决方案构建目标,x86。

任何想法如何解决这个问题?

1 个答案:

答案 0 :(得分:1)

 IntPtr ptr2 = NativeMethods.LoadLibrary("SQLite.Interop.dll");

这不是本机库,它是SQLite的.NET互操作库。它包含托管类声明。您需要使用Assembly.LoadFrom()来加载它。虽然您几乎总是喜欢将其添加为项目的参考,但很多更容易以这种方式编写代码。您可能仍然需要SetDllDirectory(),因为SQLite是用C编写的核心非托管代码,因此包装器可能需要帮助才能找到sqlite.dll。

不确定为什么要这样做,可能与64位操作系统有关。请记住,这是一个部署问题,而不是编程问题。

相关问题