WPF和非托管库加载 [英] WPF and unmanaged library loading
问题描述
最近,我遇到了一个非常奇怪的问题.
我编写了一个WPF程序,该程序与Infineon的DLL进行交互.
一切都按预期工作,但是在某个时候,我无处获得了堆栈溢出异常.
我开始确定该问题(您看到异常来自WindowsBase.dll),并且看到该问题仅在加载特定的DLL文件(通过kernel32 LoadLibrary
函数)时发生.
例如,下面的代码将导致异常发生(尽管LoadLibrary
函数返回没有错误,然后我可以使用该句柄了):
Recentrly I came across a very strange problem.
I wrote a WPF program which interacts with a DLL from Infineon.
Everything worked as expected, but at some point, I got a stack overflow exception from nowhere.
I started nailing down the issue (you see the exception comes out of WindowsBase.dll), and saw the issue only happens if I load a specific DLL file (via kernel32 LoadLibrary
function).
The following piece of code, for example, will cause the exception to happen (although the LoadLibrary
function returns with no error, and I can then use the handle):
///
/// Interaction logic for MainWindow.xaml
///
public partial class MainWindow : Window
{
[DllImport("kernel32.dll")]
public static extern IntPtr LoadLibrary(string dllToLoad);
public MainWindow()
{
InitializeComponent();
}
private void button1_Click(object sender, RoutedEventArgs e)
{
IntPtr handle = LoadLibrary("dwdiow.dll");
}
}
在此示例中,退出button1_Click()
并在一段时间后出现异常.
如果我对Windows窗体或控制台项目(而不是WPF)执行相同的操作,则不会显示错误.
请帮忙!
In this example, the button1_Click()
is exited and after some time the excption comes.
If I do the very same thing with a windows form or console projects (instead of WPF), the error does not show up.
Please help!
推荐答案
尝试使用LoadLibraryEx
代替:
Try usingLoadLibraryEx
instead:
[DllImport("kernel32.dll", CharSet=CharSet::Auto, EntryPoint="LoadLibraryEx")]
private static extern IntPtr LoadLibraryEx(string lpFileName, IntPtr hFile, uint dwFlags);
System.IntPtr moduleHandle = LoadLibraryEx(libPath, IntPtr.Zero, 0);
您需要向我们提供有关异常的更多信息,尤其是异常发生的对象/方法.实际上,您可能还想在MSDN WPF论坛上问这个问题.
You need to give us more info on the exception, specifically what opject/method it''s happening on. In fact, you might also want to ask this question on the MSDN WPF forum.
这篇关于WPF和非托管库加载的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!