Is it safe to pass std::string to C style APIs?

后端 未结 5 706
南笙
南笙 2021-01-04 23:16

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 myArray(a         


        
5条回答
  •  南方客
    南方客 (楼主)
    2021-01-05 00:00

    cStyleAPI(&myArray[0], arraySize);
    

    If your cStyleAPI receives a char* for input, that is what std::string::c_str() is for.

    If it receives a pre-allocated char* for output, then no. In that case, you should use a std::vector or std::array.

提交回复
热议问题