0

Main exe loads dll. Calls function from dll returning simple boost::any. If boost::any deleted after FreeLibrary app crash at destructor. It's ok. But I can't understand why this code also crash at r2 destructor, r2 created in main and delete doesn't need dll code. How can I save boost::any after FreeLibrary. Tried without extern "C" - same effect.

Console code:

int _tmain(int argc, _TCHAR* argv[])
{
  any r2;

  HMODULE hmod = LoadLibrary(L"dll");
  typedef any (*dllfunc)(int,int,int);
  dllfunc func = (dllfunc) GetProcAddress(hmod,"Export1");

  { 
    any r = func(1,2,3);
    r2 = r;
  }

  FreeLibrary(hmod);
  return 0;
}

Dll code:

extern "C" 
{
  DLL_API any Export1(int a,int b, int c)
  {
    return a+b+c;
  }
}

compiler Visual Studio 2005

manlio
  • 18,345
  • 14
  • 76
  • 126
micdelt
  • 21
  • 3
  • 1
    Are you sure the calling conventions match? I would never pass anything more complex than a pointer through dynamically loaded functions... – PlasmaHH Feb 06 '12 at 13:05
  • I'm with PlasmaHH. Dynamically linking doesn't mesh well with C++ ABI, template code, exceptions etc. – sehe Feb 06 '12 at 13:07
  • Found an answer, but not solution. When you copy boost::any it calls virtual method clone() which executes inside dll so virtual table of the new object resides in dll also. – micdelt Feb 06 '12 at 13:13
  • To save boost::any you need to extract content. Only serialize can help, but there is no such function. – micdelt Feb 06 '12 at 13:14
  • This is just how DLLs work. All objects that come from a DLL need to be destroyed before that DLL is unloaded -- including the instance of `any` returned by Export1. (This is one of the reasons that C++ APIs across DLLs are strongly not recommended) – Billy ONeal Aug 01 '13 at 05:05

2 Answers2

1

This depends on what actually any is. For instance it might be a shared_ptr to some object with destructor, whereas the destructor code resides in the DLL. Then all the instances of any should be destroyed prior to DLL unload.

valdo
  • 12,632
  • 2
  • 37
  • 67
0

I had the same problem with a memory manager not handling null pointers.

PixelRick
  • 149
  • 1
  • 8