C++ Passing std::string by reference to function in dll

The issue has little to do with STL, and everything to do with passing objects across application boundaries.

1) The DLL and the EXE must be compiled with the same project settings. You must do this so that the struct alignment and packing are the same, the members and member functions do not have different behavior, and even more subtle, the low-level implementation of a reference and reference parameters is exactly the same.

2) The DLL and the EXE must use the same runtime heap. To do this, you must use the DLL version of the runtime library.

You would have encountered the same problem if you created a class that does similar things (in terms of memory management) as std::string.

Probably the reason for the memory corruption is that the object in question (std::string in this case) allocates and manages dynamically allocated memory. If the application uses one heap, and the DLL uses another heap, how is that going to work if you instantiated the std::string in say, the DLL, but the application is resizing the string (meaning a memory allocation could occur)?

Leave a Comment