从DLL返回std :: wstring是否安全? [英] Is it safe to return std::wstring from a DLL?
问题描述
根据一些较旧的StackOverflow问题(无法传递std ::跨越DLL , C ++ DLL返回指向std ::的指针列表< std :: wstring> )C ++ DLL不能返回 std :: wstring
是不安全的,因为主程序不能保证定义 std :: wstring
,因此可能会导致崩溃。
According to some older StackOverflow questions ( Unable to pass std::wstring across DLL , C++ DLL returning pointer to std::list<std::wstring> ) it's not considered safe for a C++ DLL to return a std::wstring
because there's no guarantee the main program has the same definition of std::wstring
and therefore it might cause a crash.
但是,在 http://en.cppreference.com/w/cpp/string/basic_string ,它似乎 std :: wstring
现在可以与 WCHAR
数组互换使用:
However, in http://en.cppreference.com/w/cpp/string/basic_string , it seems std::wstring
can be used interchangeably with a WCHAR
array now:
(由于C ++ 11)
basic_string的元素连续存储,也就是说,对于[0,s.size())中的任何n,对于basic_string s,& *(s.begin()+ n)==& * s.begin()+ n)可以将一个指向s [0]的指针传递给希望指向CharT []数组的第一个元素的指针的函数。
(Since C++11) The elements of a basic_string are stored contiguously, that is, for a basic_string s, &*(s.begin() + n) == &*s.begin() + n for any n in [0, s.size()), or, equivalently, a pointer to s[0] can be passed to functions that expect a pointer to the first element of a CharT[] array.
我已经通过将& s [0]
传递给预期一个 WCHAR *
缓冲区的WINAPI函数来测试它似乎工作( std :: wstring
正确填充了WINAPI的结果)。所以因为现在, std :: wstring
可以显然被视为一个 WCHAR
数组,我决定重新访问这个问题:can从DLL中安全地返回一个 std :: wstring
为什么或为什么不这样做?
I've tested this by passing &s[0]
to a WINAPI function that expected a WCHAR*
buffer and it appeared to work (the std::wstring
was correctly populated with the results of the WINAPI). So since std::wstring
can apparently be treated like a WCHAR
array now, I decided to revisit this question: can a std::wstring
be safely returned from a DLL? Why or why not?
推荐答案
在DLL边界上传递C ++对象时,没有任何改变。与以前相同的原因仍然不允许。边界另一边的模块可能对类有不同的定义。
Nothing has changed with regards passing C++ objects across DLL boundaries. That is still not allowed for the same reason as before. The module on the other side of the boundary may have a different definition of the class.
& s [0]
是一个有效的可修改的指向字符数组的指针并不真正相关。因为 std :: basic_string
不仅仅是一个字符数组。
The fact that &s[0]
is a valid modifiable pointer to character array is not really relevant. Because a std::basic_string
is a lot more than just an array of characters.
请记住, std :: basic_string
的每个实现都可以有不同的内部存储。对于 operator []
可以有不同的实现。可以分配一个不同的堆。等等。
Remember that each implementation of std::basic_string
can have different internal storage. Can have a different implementation for operator[]
. Can be allocated off a different heap. And so on.
我认为可以安全地假设在一般DLL边界内传递C ++对象永远不会有效。如果您保证边界的两边都与相同的运行时实例链接,那只能是可行的。
I think it is safe to assume that it will never be valid to pass C++ objects across general DLL boundaries. It is only viable if you guarantee that both sides of the boundary are linked against the same runtime instance.
这篇关于从DLL返回std :: wstring是否安全?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!