Re: std::string and C APIs
On Feb 21, 6:19 pm, Early Ehlinger
<spamsink.early.spams...@respower.com> wrote:
I'm calling a C API that expects a char* and a buffer size for output,
like so:
int c_style_api( char* output_buffer , int output_buffer_size );
I'm trying to wrap it in a more C++-ish manner for a function signature
that looks like this:
std::string cpp_wrapper( );
My current approach is not something I'm particularly fond of:
std::string cpp_wrapper( ) {
int size = calculate_size( );
std::vector< char > buffer( size );
int check = c_style_api( &*buffer.begin() , size );
throw_on_error( check );
std::string result( buffer.begin() , buffer.end() );
return result;
}
Depending on whether or not you need this to be thread-safe, you could
make the vector buffer static, which would cut down on the number of
memory allocations (i.e. just s single buffer would be used, and it
would never shrink, but it would grow to meet your needs):
std::string cpp_wrapper( )
{
static std::vector<char> buffer;
buffer.resize(calculate_size());
int check = c_style_api(&buffer.front(), buffer.size());
throw_on_error( check );
return std::string(buffer.begin(), buffer.end());
}
But again, this is not reentrant, as it relies on static data.
--
[ See http://www.gotw.ca/resources/clcm.htm for info about ]
[ comp.lang.c++.moderated. First time posters: Do this! ]