Is it possible to return std :: wstring from a DLL?

According to some older StackOverflow questions ( Cannot pass std :: wstring via DLL , C ++ DLL returns a pointer to std :: list <std :: wstring> ), it is not considered safe for C ++ DLL to return std::wstring , because there is no guarantee that the main program has the same definition of std::wstring , and therefore this may cause a crash.

However, at http://en.cppreference.com/w/cpp/string/basic_string it seems that std::wstring can be used interchangeably with a WCHAR array:

(Since C ++ 11) The elements of basic_string are stored adjacent, that is, for basic_string s, & * (s.begin () + n) == & * s.begin () + n for any n from [0, s. size ()), or, equivalently, a pointer to s [0] can be passed to functions that expect a pointer to the first element of the CharT [] array.

I tested this by passing &s[0] to the WINAPI function, which was expecting a WCHAR* buffer, and it seemed to work ( std::wstring was correctly populated with WINAPI results). Since std::wstring can apparently be viewed as a WCHAR array, I decided to return to this question: can std::wstring safe to return from a DLL? Why or why not?

+4
c ++ c ++ 11 dll std wchar
Dec 17 '13 at 23:44
source share
1 answer

Nothing has changed with respect to passing C ++ objects across DLL boundaries. This is still not allowed for the same reason as before. A module on the other side of the boundary may have a different class definition.

The fact that &s[0] is a valid modifiable pointer to an array of characters does not really matter. Because std::basic_string much more than just an array of characters.

Remember that each std::basic_string may have different internal storage. May have a different implementation for operator[] . May stand out from another heap. And so on.

I think it is safe to assume that it will never be permissible to pass C ++ objects across common DLL boundaries. This is only possible if you guarantee that both sides of the boundary are associated with the same instance of the runtime.

+6
Dec 17 '13 at 23:47
source share



All Articles