你能在第三方dll中使用std::string吗?
Can you use std::string in a 3rd party dll?
我一直在寻找问题的答案,但似乎大多数人都有兴趣通过。dll边界传递std::string。但是我更感兴趣的是在我正在创建的。dll中的类中使用std::string。
我正在向论坛上的一群人发布我的.dll(电子邮件),所以我的问题是你可以在.dll中使用std::string而不受编译器需要相同,版本,CRT需要相同等限制。
你能举例说明什么是不安全的,什么是安全的吗?
示例:"downloader"使用SetSender函数是否安全?
Mail.h
class _declspec(dllexport) Mail {
struct ENVELOPE {
std::wstring SenderEmail; //Should the type be LPWSTR or can it safely be std::wstring
LPWSTR SenderName;
}Envelope;
public:
int SetSender(LPWSTR SenderEmail);
Mail();
~Mail();
};
Mail.cpp
#include "stdafx.h"
#include "Mail.h"
int CoffeeBeans::Mail::SetSender(LPWSTR Email) {
//Pass LPWSTR instead of std::wstring across .dll boundary
if (Email == nullptr || lstrcmp(Email, L"") == 0) {
throw L"Email was either nullptr or empty.";
}
this->Envelope.SenderEmail = SenderEmail;
return 0;
}
使用指向字符串缓冲区的指针,如LPWSTR
或wchar_t*
等,只要您的dll代码没有调用未指定的行为(内存被正确分配,指针被初始化,您没有将指针传递给本地缓冲区等),则始终是安全的。只要您的dll和主机使用相同的CRT版本,使用std::string
将是安全的仅。如果版本不同,您的字符串可能会在任何执行阶段导致访问违规(通常发生在字符串销毁时)。您可以通过分发您的dll源或为所有现有的CRT编译不同的dll版本来确保CRT匹配(例如,Oracle为他们的OCCI
库这样做)。当然,如果客户端不使用c++,这种方法是行不通的。
相关文章:
- cppcheck在const std::string[]上引发警告
- 将std::string传递给WriteConsole API
- 为std::string的某个索引赋值
- 使用 std::string () const 函数启动线程或未来
- 当我们进行一些操作时,应该使用什么'std::string'或'std::stringstream'?
- 如何更改大小(std::string)
- std::string 的对象真的可以移动吗?
- SegFault 同时使用 std::string::operator+= 和函数作为参数
- 无法从 std::string 中提取C++ Unicode 符号
- std::string 构造函数如何处理固定大小的 char[]?
- 真的没有来自 std::string_view 的 std::string 的显式构造函数吗?
- 将C++ std::string 转换为 UTF-16-LE 编码的字符串
- 重载 + 自己的类和 std::string 的运算符
- 如何使用 std::string 作为 QHash 的键?
- 将日语 wstring 转换为 std::string
- 可以从std::string继承以提供类型一致性吗
- 构造函数采用std::string_view与std::string并移动
- 在共享缓冲区内存中创建 ::std::string 对象
- std::string.size() 未知行为
- Valgrind 在 std::string::swap 中报告 SIGILL