c++ - 如何在托管 dll 中重新初始化 native 代码

标签 c++ c dll

为了测试现有的应用程序,我编写了一个可以加载到我们的模拟应用程序中的 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/

相关文章:

android - C++ 模板类显式实例化因 GCC/NDK 而失败

c++ - 在队列中插入 vector 元素

c++ - MFC 按钮单击响应转义键

c - C语言求和函数

c# - 为什么是 "C:\Windows\Microsoft.NET\assembly\GAC_32..."而不是 "C:\Windows\assembly\GAC_32"

c++ - 比较期间 C++ bool 值是否转换为整数?

iphone - xcode 中的多个实例 if 语句(iphone)

c - 试图实现一堆结构

c++ - 当被系统 DLL 调用时,Hooked VirtualAlloc 返回 nullptr

c++ - 尝试在 DLL 中使用静态库的 Visual Studio 链接器错误(LNK2038、LNK2005)