gpt4 book ai didi

来自 native C++ 加载的 DLL 的 C# 形式

转载 作者:塔克拉玛干 更新时间:2023-11-03 02:19:10 24 4
gpt4 key购买 nike

这个问题来自这个线程:Native C++ use C# dll via proxy C++ managed dll

简而言之,我正在通过 DLL 将(我的)C# 扩展加载到 native 进程中。扩展需要显示一个表单,以便用户可以控制它。我使用的是标准 .NET 表单,没有第 3 方库或任何东西,而且我的表单没有显示。更糟糕的是,它会挂起目标进程。它没有使用任何 CPU,所以我感觉它在等待某个函数返回,但从未这样做过。

同样有趣的是弹出了“Initialize method”消息框,但没有弹出“Test”消息框。我已经测试了所有我能想到的东西(STAthread、线程、DisableThreadLibraryCalls,以及不同的代码位置),一直到星期天。我倾向于认为这是 Win32 互操作的一些模糊细节,但我找不到任何似乎会导致这些症状的东西。

你们中的一位专家可以看一下我的代码并指出问题所在吗?

/// <summary>
/// Provides entry points for native code
/// </summary>
internal static class UnmanagedExports
{
[UnmanagedFunctionPointer(System.Runtime.InteropServices.CallingConvention.StdCall)]
public delegate int SendRecv([MarshalAs(UnmanagedType.SafeArray)]byte[] ByteArray, UInt64 Len);

[STAThread]
[DllExport("Initialize", CallingConvention.StdCall)]
public static int Initialize(IntPtr hInstance, SendRecv Send, SendRecv Recv)
{
return DLLinterface.Initialize(hInstance, Send, Recv);
}

[DllExport("Terminate", CallingConvention.StdCall)]
public static void Terminate()
{
DLLinterface.Terminate();
}
}

internal class DLLinterface
{
static System.Threading.Thread uiThread;

[STAThread]
internal static int Initialize(IntPtr hInstance, UnmanagedExports.SendRecv Send, UnmanagedExports.SendRecv Recv)
{
MessageBox.Show("Initialize method");
try
{
uiThread = new System.Threading.Thread(Run);
uiThread.Start();
}
catch (Exception ex)
{
MessageBox.Show("Failed to load: " + ex.Message, "Infralissa error", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
return 1;
}

[STAThread]
private static void Run()
{
MessageBox.Show("Test");

Application.EnableVisualStyles();
Application.SetCompatibleTextRenderingDefault(false);
Application.Run(new Form1());
}

internal static void Terminate()
{
MessageBox.Show("Terminating.");
if (uiThread.IsAlive)
uiThread.Abort();
}
}

最佳答案

看来是目标本身出了问题。它不是直接加载扩展,而是加载 native “exensionManager.dll”,幸运的是,他们使用 DllMain 加载我的扩展。换句话说,我试图在 loaderlock 下加载一个表单并遇到了死锁。 NET 尝试加载其他程序集。

答案很简单,我必须在新线程上显示表单。然而,.NET 的线程也被挂起,因为它也需要加载库,这会导致死锁。

最后,我不得不求助于 vanilla P/Invoke 直接调用 CreateThread(),但表单终于出现了。

关于来自 native C++ 加载的 DLL 的 C# 形式,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11304072/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com