如何使用 inplace const char* 作为 std::string 内容
How to use inplace const char* as std::string content
我正在从事一个嵌入式软件项目。很多字符串都存储在闪存中。我会使用这些字符串(通常是 const char*
或 const wchar*
)作为 std::string
的数据。这意味着我想避免因为内存限制而创建原始数据的副本。
扩展用途可能是通过字符串流直接从闪存中读取闪存数据。
不幸的是,示例无法正常工作:
const char* flash_adr = 0x00300000;
size_t length = 3000;
std::string str(flash_adr, length);
任何想法将不胜感激!
如果您愿意使用特定于编译器和库的实现,这里有一个适用于 MSVC 2013 的示例。
#include <iostream>
#include <string>
int main() {
std::string str("A std::string with a larger length than yours");
char *flash_adr = "Your source from the flash";
char *reset_adr = str._Bx._Ptr; // Keep the old address around
// Change the inner buffer
(char*)str._Bx._Ptr = flash_adr;
std::cout << str << std::endl;
// Reset the pointer or the program will crash
(char*)str._Bx._Ptr = reset_adr;
return 0;
}
它将打印Your source from the flash
。
想法是保留一个 std::string 能够在你的 flash 中安装字符串并不断改变它的内部缓冲区指针。
您需要为您的编译器自定义它,而且一如既往,您需要非常非常小心。
我现在已经使用了 CPP 核心指南 (https://github.com/isocpp/CppCoreGuidelines/blob/master/CppCoreGuidelines.md). GSL provides a complete implementation (GSL: Guidelines Support Library https://github.com/Microsoft/GSL) 中描述的 string_span。
如果您知道您的字符串在闪存中的地址,您可以直接使用该地址和以下构造函数来创建一个 string_span。
constexpr basic_string_span(pointer ptr, size_type length) noexcept
: span_(ptr, length)
{}
std::string_view 可能已经完成了与 Captain Obvlious (https://whosebug.com/users/845568/captain-obvlious) 相同的工作,这是我最喜欢的评论。
我对这个解决方案很满意。它在性能方面表现良好,包括提供良好的可读性。
我正在从事一个嵌入式软件项目。很多字符串都存储在闪存中。我会使用这些字符串(通常是 const char*
或 const wchar*
)作为 std::string
的数据。这意味着我想避免因为内存限制而创建原始数据的副本。
扩展用途可能是通过字符串流直接从闪存中读取闪存数据。
不幸的是,示例无法正常工作:
const char* flash_adr = 0x00300000;
size_t length = 3000;
std::string str(flash_adr, length);
任何想法将不胜感激!
如果您愿意使用特定于编译器和库的实现,这里有一个适用于 MSVC 2013 的示例。
#include <iostream>
#include <string>
int main() {
std::string str("A std::string with a larger length than yours");
char *flash_adr = "Your source from the flash";
char *reset_adr = str._Bx._Ptr; // Keep the old address around
// Change the inner buffer
(char*)str._Bx._Ptr = flash_adr;
std::cout << str << std::endl;
// Reset the pointer or the program will crash
(char*)str._Bx._Ptr = reset_adr;
return 0;
}
它将打印Your source from the flash
。
想法是保留一个 std::string 能够在你的 flash 中安装字符串并不断改变它的内部缓冲区指针。
您需要为您的编译器自定义它,而且一如既往,您需要非常非常小心。
我现在已经使用了 CPP 核心指南 (https://github.com/isocpp/CppCoreGuidelines/blob/master/CppCoreGuidelines.md). GSL provides a complete implementation (GSL: Guidelines Support Library https://github.com/Microsoft/GSL) 中描述的 string_span。
如果您知道您的字符串在闪存中的地址,您可以直接使用该地址和以下构造函数来创建一个 string_span。
constexpr basic_string_span(pointer ptr, size_type length) noexcept
: span_(ptr, length)
{}
std::string_view 可能已经完成了与 Captain Obvlious (https://whosebug.com/users/845568/captain-obvlious) 相同的工作,这是我最喜欢的评论。
我对这个解决方案很满意。它在性能方面表现良好,包括提供良好的可读性。