You can get a pointer to the string buffer by simply calling std::string.c_str()
. That will return a const char*
(where char
is an int8_t
) that you can effectively use as a byte[]
. Keep in mind though that the pointer returned is pointing to memory managed by the string object, so if you change anything in the original string class, you will invalidate the pointer. Also since it's a pointer to a const char
, you shouldn't change any values in the buffer. So if you need more permanent memory, or need a buffer you can modify, a better way to accomplish your goal would be to-do (using gcc, which shouldn't be a problem since you're on Ubuntu):
std::string my_string;
char string_array[my_string.length() + 1];
strcpy(string_array, my_string.c_str());
Now use the string_array
as your memory buffer.
If you need to return the buffer from a function, you're going to have to allocate the buffer on the heap and return a pointer. That also means you're going to have to call delete []
on the pointer as well after you're done with it, or else you're going to end up with a memory leak. So you could do the following:
#include <string>
#include <cstring>
char* return_buffer(const std::string& string)
{
char* return_string = new char[string.length() + 1];
strcpy(return_string, string.c_str());
return return_string;
}
//now use in code
int main()
{
std::string some_string = "Stuff";
char* buffer = return_buffer(some_string);
//...do something with buffer
//...after you're done with the buffer to prevent memory leak
delete [] buffer;
return 0;
}