c_str()返回空字符串
由于某种原因c_str()返回空字符串,参数 const chart ** out_function
将保存诸如 fopen
之类的文件操作的方法名称,所以基本上我要做的是将字符串转换为c_str(),但是下面得到的是一个空字符串
For some reason c_str() returns empty string, the parameter const chart**out_function
will hold a method name for file operations like fopen
so basically what I do is converting a string I have to c_str() but I get an empty string below is how I do the calls
在这一部分中,我只是准备一个带有操作名称的字典,您会注意到我只是以字符串形式发送"fopen"
In this part I just prepare a dictionary with an operation name, as you can notice I am just sending "fopen" as string
pp::VarDictionary fileOp;
pp::VarArray args;
args.Set(0, "filename.txt");
args.Set(1, "wb");
fileOp.Set("args", args);
fileOp.Set("cmd", "fopen");
此函数将解析上面发送的字典,并在 out_params
This function will parse the dictionary sent above and return the name of the function in out_function
and args
in out_params
int ParseMessage(pp::Var message, const char** out_function,
pp::Var* out_params) {
我使用此行代码将字符串转换为c_string,但它返回空文本
I use this line of code to convert the string to c_string, but It returns empty text
*out_function = cmd_value.AsString().c_str();
这是完整的代码,它基于Google Native Client,但同时又是标准的C/C ++代码
here is the full code, it is based on Google Native Client but at the same time it is standard C/C++ code
c_str()
的结果仅在 std :: string
对象符合以下条件时有效产生的结果是有效的.
The result of c_str()
is only valid as long as the std::string
object that produced that result is valid.
在您的情况下, AsString()
调用会生成一个临时 std :: string
对象,然后该对象立即销毁.之后,该 c_str()
调用的结果不再有意义.尝试访问该指针所指向的内存会导致未定义的行为.
In your case, AsString()
call produces a temporary std::string
object which is then immediately destroyed. After that the result of that c_str()
call no longer makes any sense. Trying to access the memory pointed by that pointer leads to undefined behavior.
不要尝试存储由 c_str()
返回的指针.如果长时间需要该字符串作为C字符串,请自己为其分配内存缓冲区,然后将 c_str()
的结果复制到该缓冲区.
Don't attempt to store the pointer returned by c_str()
. If you need that string as a C-string for an extended period of time, allocate memory buffer for it yourself and copy the result of c_str()
to that buffer.
另一个更好的想法是不要急于转换为C字符串.返回结果为 std :: string
,并在最后一刻调用它: c_str()
:当您真正需要C字符串时.
Another (much better) idea would be not to rush the conversion to C-string. Return the result as std::string
and call c_str()
on it at the very last moment: when you reall really really need a C-string.