我一直在寻找我的问题的答案,但似乎大多数人都对跨 .dll 边界传递 std::string 感兴趣。但我更感兴趣的是在我正在创建的 .dll 中的类中使用 std::string。
我正在向论坛上的一群人发布我的 .dll(通过电子邮件发送),所以我的问题是你可以在 .dll 中使用 std::string 而没有像编译器需要相同这样的限制,版本,CRT需要相同等。
你能举例说明什么是不安全的,什么是安全的吗?
示例:“下载器”使用 SetSender 函数是否安全?
邮件.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();
};
邮件.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++,这种方法当然行不通。
关于c++ - 你能在第 3 方 dll 中使用 std::string 吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40211437/