它是安全传递的std ::字符串到C风格的API? [英] Is it safe to pass std::string to C style APIs?

查看:132
本文介绍了它是安全传递的std ::字符串到C风格的API?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这是明确的C ++来的std ::载体传递给期望的输出数组,像这样因为性病::向量是连续Ç的API:

It is well defined C++ to pass std::vector to C APIs that expect an output array like so because std::vector is contiguous:

std::vector<char> myArray(arraySize);
cStyleAPI(&myArray[0], arraySize);

它是安全传递的std ::字符串以同样的方式到C API的?是否有标准的C ++ 03的任何保证为std :: string是连续并以同样的方式作为工作的std :: vector所在这种情况呢?

Is it safe to pass std::string in the same manner to C APIs? Is there any guarantee in standard C++03 that std::string is contiguous and works in the same way as std::vector does in this situation?

推荐答案

如果C API函数需要只读到的std ::字符串的内容访问然后使用的std ::字符串:: c_str()成员函数传递字符串。这是保证是一个空结尾的字符串。

If the C API function requires read-only access to the contents of the std::string then use the std::string::c_str() member function to pass the string. This is guaranteed to be a null terminated string.

如果您打算使用的std ::字符串的参数,C ++ 03并不能保证存储的字符串在内存中连续的,但C ++ 11呢。后者是通过确定要修改字符串运算符[] 只要你的不要修改终止空字符

If you intend to use the std::string as an out parameter, C++03 doesn't guarantee that the stored string is contiguous in memory, but C++11 does. With the latter it is OK to modify the string via operator[] as long as you don't modify the terminating NULL character.

这篇关于它是安全传递的std ::字符串到C风格的API?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆