Ahmad Siavashi Ahmad Siavashi - 4 years ago 136
C++ Question

Memory relocation for vector across DLL boundaries

This question is not a duplicate to those with a similar name in SO

It is well-known that if DLLs are statically linked (/MT flag in
MSVC), the DLL that has allocated the memory MUST deallocate it; otherwise
memory deallocation will cause runtime errors.

Here is the problem:

  • I have allocated a
    in DLL, say

  • A
    passes the vector to DLL, say

  • DLL
    inserts data into the vector.

  • Now, if DLL
    tries to destruct the vector, it will face errors.

I have figured out that if I use
before passing the vector to
, to have the vector big enough to hold the data and prevent memory reallocation - that normally happens during item insertion - then I won't get errors in
when trying to destruct the vector. It seems that, in case of memory reallocation,
allocates for the vector in its own heap. Is my reasoning wrong? How can I prevent this?

Answer Source

The easiest way round this is to hide the vector inside methods exposed from the dll so you can get a const vector to view in other dlls, but not modify it. Then create a new function in dll B that adds the entry to the vector on the caller's behalf.

So your vector remains hidden inside dll B for all modifications.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download