如何将std::stringbuf强制转换为char数组
How to cast a std::stringbuf into an array of char?
我在这里要做的是将stringbuf
对象转换为char数组。
我这样做是为了将char数组发送到不理解std::stringbuf
类型的C
接口。
下面是我的一部分代码来说明这个问题:
std::stringbuf buffer;
char * data;
//here i fill my buffer with an object
buffer >> Myobject;
//here is the function I want to create but I don't know if it's possible
data = convertToCharArray(buffer);
//here I send my buffer of char to my C interface
sendToCInterface(data);
如果你没有严格的零拷贝/高性能要求,那么:
std::string tmp = buffer.str();
// call C-interface, it is expected to not save the pointer
sendToCharInterface(tmp.data(), tmp.size());
// call C-interface giving it unique dynamically allocated copy, note strdup(...)
sendToCharInterface(strndup(tmp.data(), tmp.size()), tmp.size());
如果你确实需要它更快(但仍然有stringbuf在路上),那么你可以看看stringbuf::pubsetbuf()的方向。
正如Kiroxas在第一条评论中建议的那样,尽量避免使用中间变量:
sendToCInterface(buffer.str().c_str());
…变量越少,混淆越少;-)
如果您想将std::stringbuf转换为char指针,我认为您可以直接执行
std::string bufstring = buffer.str();
获取字符串,并使用
将其转换为c风格的字符串bufstring.c_str()
传递一个字符指针给函数
相关文章:
- 将无符号char*转换为std::istream*C++
- 为什么这个函数将"const char*"转换为"void* const"而不是"const void*"
- 使用char类型将decimal转换为string,将string转换为decimal
- 如何在对<char>C++程序进行逆向工程的同时将 std::basic_string 转换为 Rust 可读值?
- 将函数参数"const char*"转换为"std::string_view"是
- 如何在保持其值的同时将 c++ 无符号字符变量转换为 char 变量
- 需要帮助在 c++ 中将字符串转换为字符 ----错误 "const char *" 类型的值不能用于初始化 "char" 类型的实体
- 如何在不强制转换每个参数的情况下删除初始值设定项列表中从 int 到 char 的缩小转换?
- C ++如何在使用"tolower"时将char转换为int
- 有没有办法在C++的赋值中将"char**"转换为"double"?
- 如何使用多次 memcpy 转换回 std::vector<unsigned char>?
- 将"uint8_t"(从套接字读取)隐式转换为"char"安全吗
- JavaCPP 错误:无法将参数"1"的"char*"转换为"Abc*
- 将传入的网络"char*"数据转换为"uint8_t"并返回的安全方法是什么?
- 转换char*时的值不同
- Boost Python 不会自动转换 char* 数据成员
- 除了转换char*之外,还有更好的方法来获得一个变量值吗?
- 如何跨平台转换char*到long long(64位)
- 用atof转换char数组中的浮点数
- C转换char[]为时间戳;