Sign in to follow this  
Simplicity

STL string across DLL

Recommended Posts

Simplicity    158
Can I use STL across DLLs? Let's say I have DLL1 that declares: class DLL1_EXPORT A { private: std::string m_String; } And DLL2 imports class A and inherits from it: class DLL2_EXPORT B : public A { } Will this cause problem when we start using these classes? What about for other containers like map, list, etc? This link describes several things and it applies to VC++ 5 and 6. What about for .NET? [a href="http://support.microsoft.com/default.aspx?scid=kb;en-us;168958"]Link[/a]

Share this post


Link to post
Share on other sites
blaze02    100
I'm not exactly sure how you are inheriting across DLLs (I haven't worked with them much). I do know that DLLs declare variables on a per-instance basis. I.E: if prog1 and prog2 use the same DLL, the variables in the DLL are created twice and do not collide.

Share this post


Link to post
Share on other sites
Evil Steve    2017
You can only use STL containers (std::strings included) if:
  • You're runing Linux

  • You link to the DLL version of the CRT from both the EXE and DLL.

  • Or you only pass by STL containers by const reference

In Windows, each module (EXE or DLL) gets its own heap. You can't allocate something from one heap and free it in another. STL containers cause issues, because they're constantly allocating and releasing memory. If you pass a std::string to a function in a DLL, and it tries to append data to it, and it has to reallocate memory then it'll have to free the old memory. That usually results in a call to delete[], which - because it's called in the DLL - tries to free the memory from the DLLs heap. The memory was allocated by the EXE, so boom. Access Violation.
This problem doesn't occur in Linux because it doesn't have the same notion of heaps, and there isn't a problem in allocating memory in a DLL (Well, shared object) and freeing it in a EXE.

Using the DLL version of the CRT solves this problem because then both the DLL and EXE link to the same instance of the CRT DLL, and call new and delete from the same heap - the heap in the CRT DLL.

Share this post


Link to post
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now

Sign in to follow this