对的调用ImGui::InputText()
采用一个char
数组,我需要从 a 初始化该数组std::string
,然后将内容传输回std::string
. 最简单的形式:
char buf[255]{};
std::string s{"foo"};
void fn() {
strncpy( buf, s.c_str(), sizeof(buf)-1 );
ImGui::InputText( "Text", buf, sizeof(buf) );
s=buf;
}
Run Code Online (Sandbox Code Playgroud)
然而,让两个缓冲区(buf
以及其中分配的缓冲区std::string
)都做同样的事情似乎很浪费。我可以通过仅使用一个简单的包装器“X”来避免buf
缓冲区以及从缓冲区进行复制吗?std::string
我不关心效率,我只想要调用站点最简单的代码。这段代码确实有效,但它安全吗?有更好的方法吗?
class X {
public:
X(std::string& s) : s_{s} { s.resize(len_); }
~X() { s_.resize(strlen(s_.c_str())); }
operator char*(){ return s_.data(); }
static constexpr auto len() { return len_-1; }
private:
std::string& s_;
static constexpr auto len_=255;
};
std::string s{"foo"};
void fn() {
ImGui::InputText( "Text", X(s), X::len() );
}
Run Code Online (Sandbox Code Playgroud)
S.M*_*.M. 11
如果您想使用InputText()
任何std::string
自定义动态字符串类型,请参阅misc/cpp/imgui_stdlib.h 和imgui_demo.cpp 中的注释。
杂项/cpp/imgui_stdlib.h
namespace ImGui
{
// ImGui::InputText() with std::string
// Because text input needs dynamic resizing, we need to setup a callback to grow the capacity
IMGUI_API bool InputText(const char* label, std::string* str, ImGuiInputTextFlags flags = 0, ImGuiInputTextCallback callback = NULL, void* user_data = NULL);
IMGUI_API bool InputTextMultiline(const char* label, std::string* str, const ImVec2& size = ImVec2(0, 0), ImGuiInputTextFlags flags = 0, ImGuiInputTextCallback callback = NULL, void* user_data = NULL);
IMGUI_API bool InputTextWithHint(const char* label, const char* hint, std::string* str, ImGuiInputTextFlags flags = 0, ImGuiInputTextCallback callback = NULL, void* user_data = NULL);
}
Run Code Online (Sandbox Code Playgroud)
你的第一个代码
std::string s{"foo"};
void fn() {
ImGui::InputText( "Text", &s );
}
Run Code Online (Sandbox Code Playgroud)
阅读手册会产生奇迹。
归档时间: |
|
查看次数: |
23299 次 |
最近记录: |