在Visual Studio 2015中使用和导出std::string和std::vector<std::string>

3

使用VS2013和适当的导出宏,我可以使用此示例代码导出std :: string和std :: vector:

#ifdef _MSC_VER
// Explicit template exports.
c_EXPORT_TEMPLATE template class c_EXPORT std::allocator<char>;
c_EXPORT_TEMPLATE template struct c_EXPORT std::char_traits<char>;
c_EXPORT_TEMPLATE template class c_EXPORT std::basic_string<char, std::char_traits<char>, std::allocator<char> >;
c_EXPORT_TEMPLATE template class c_EXPORT std::allocator<std::basic_string<char, std::char_traits<char>, std::allocator<char> > >;
c_EXPORT_TEMPLATE template class c_EXPORT std::vector<std::basic_string<char, std::char_traits<char>, std::allocator<char> >, std::allocator<std::basic_string<char, std::char_traits<char>, std::allocator<char> > > >;
#endif

(compilable testcase here: https://github.com/rleigh-dundee/dlltest)-这既可以作为静态库使用,也可以作为DLLs使用
cmake -G "Visual Studio 12 2013 Win64" -DBUILD_SHARED_LIBS=ON|OFF /path/to/source 在使用VS2015编译DLL时,与std::string相关的警告会出现:
c:\users\rleigh\libtest\a.h(30): warning C4251: 'std::_String_alloc>::_Mypair': class 'std::_Compressed_pair>,std::_String_val>,true>' needs to have dll-interface to be used by clients of class 'std::_String_alloc>'
对于std::vector也是类似的问题:
C:\Program Files (x86)\Microsoft Visual Studio 14.0\VC\include\vector(679): warning C4251: 'std::_Vector_alloc>::_Mypair': class 'std::_Compressed_pair,std::allocator>>>,std::_Vector_val,std::allocator>>>,true>' needs to have dll-interface to be used by clients of class 'std::_Vector_alloc>'
虽然在这个虚构的测试用例中这些警告看起来是无害的,测试运行良好,但我想修复它们。
更严重的是,如果我使用静态库替换DLL,则链接失败:
c.lib(c.obj) : error LNK2001: unresolved external symbol "public: static unsigned __int64 const std::basic_string,class std::allocator >::npos" (?npos@?$basic_string@DU?$char_traits@D@std@@V?$allocator@D@2@@std@@2_KB)
我在尝试使用VS2015构建其他项目时也遇到了这个后一个错误。
我的问题是:
1.VS2015中的string和vector类具体变化了什么?
2.我是否正确地导出了这些string和vector类? 我认为它符合此处的指南:https://support.microsoft.com/en-us/kb/168958 3.我应该做哪些更改才能修复静态链接错误和DLL警告,以便在VS2015和VS2013中都能正常工作?(我将留下2012年以处理另一组问题)。
感谢您的见解, 罗杰

https://dev59.com/EnRA5IYBdhLWcg3w9izq?rq=1 - Cory Kramer
谢谢,但我已经遵循了大部分的指导。这并没有解决静态链接的问题,也没有解决VS2015中的更改。 - Roger Leigh
这基本上是 https://dev59.com/x2Eh5IYBdhLWcg3wHAND 的重复。 - Ben Voigt
@BenVoigt请注意,您链接的帖子更为普遍,并涉及可能使用不同的VC版本;而这里的问题并非如此。 - Roger Leigh
2个回答

1

无论如何都不能使这在多个版本的Visual C++中工作。每个版本中类定义都不同,因此如果尝试将混合版本链接在一起,则违反了一个定义规则。

通过DLL边界导出标准库对象永远不会有好结果,建议您找到更简单的方法(仅使用标准布局类型)来传递数据。


2
请注意,此问题不涉及在多个Visual C++版本之间使事情正常工作。它是关于导出和使用STL类型以在单个VC版本中使用。 - Roger Leigh

0

移除对 std::char_traits<char> 的导出:

b_EXPORT_TEMPLATE template struct b_EXPORT std::char_traits<char>;

解决静态链接错误。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接