为了测试现有的应用程序,我编写了一个可以加载到我们的模拟应用程序中的 dll。一切正常,直到我想从 dll 中重置现有应用程序。虽然 main() 重新启动了,但似乎内存没有重置/初始化。 目标是在现有应用程序中尽可能少地更改,所以实际上我不想重写应用程序以在启动时初始化其变量。除此之外,所有局部静态变量也保留它们的旧值。
下面是我如何从 dll 中调用现有应用程序的示例。
void TimerThread::Run(void)
{
while(true)
{
if ((nullptr != mpMainThread) && (mpMainThread->ThreadState == System::Threading::ThreadState::Stopped))
{
// Cleanup MainThread when thread has stopped
delete mpMainThread;
mpMainThread = nullptr;
}
if (nullptr == mpMainThread)
{
// (Re)create MainThread in which the existing application is executed
mpMainThread = gcnew System::Threading::Thread(gcnew System::Threading::ThreadStart(&Main));
mpMainThread->Priority = System::Threading::ThreadPriority::Highest;
mpMainThread->Start();
}
dtStartTime = System::DateTime::Now; // Keep track when started.
if (nullptr != mpMainThread)
{
//Simulate timertick in existing application
main_callback_timer_elapsed();
}
dtEndTime = System::DateTime::Now;
iDuration = dtEndTime->Millisecond - dtStartTime->Millisecond; // Determine execution time.
System::Threading::Thread::Sleep(((TIMER_INTERVAL - iDuration) > 0) ? (miInterval - iDuration) : 0); // Set sleep time depending on time spent
}
}
void TimerThread::Main(void)
{
main(); // Run main off existing application
}
void TimerThread::Reset(void)
{
mpMainThread->Abort(); // Reset existing application by aborting MainThread
}
现有应用程序的主体是相当普遍的。下面是 main() 的指示。
int main(void)
{
static char test = 0;
init_stuff();
while(true)
{
test = 1;
do_stuff();
while(!timer_tick)
{
check_timer();
}
timer_tick = FALSE;
}
}
静态测试变量初始化为 0,在无限循环中设置为 1。当从 dll 中重置应用程序时,主程序重新启动,但测试变量保持值 1。显然我希望在重置应用程序时将此变量重置为 0。
有什么想法吗?
最佳答案
如果 native DLL 不提供重置其状态的函数,那么您将不得不卸载 DLL,然后重新加载它。如果您使用隐式链接,那是不可能的。您必须使用显式链接:LoadLibrary、GetProcAddress 等。
我假设 native 代码包含在一个单独的 DLL 中。如果不是这种情况,那么您就完全陷入困境了。
关于c++ - 如何在托管 dll 中重新初始化 native 代码,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10023553/