On Apr 18, 3:43 am, Carlos Moreno <cm_n...@[EMAIL PROTECTED]
> wrote:
> I'm creating a C++ wrapper for a C library; in this one function,
> I need to return a string. The underlying C library expects me
> to pass it a pointer where to put the result; that pointer needs
> to be dynamically allocated in the general case.
>
> So, my function goes more or less like this:
>
> string f()
> {
> char * result = new char [ ... ];
>
> int length = call_c_function (result, .... other
> parameters ... );
> // the function places the result string in the memory
> // pointed to by result, and it returns the length of the
> string
>
> return string (result, result + length);
>
> }
I won't enter into the question of whether your performance concerns
are justifiable - I'm only prepared to present what I consider good
practice when they are.
There are three scenarios:
1) you know a maximum buffer size you need to sup****t at compile time:
string f()
{
char buffer[MAX];
int len = c_function(buffer, ...);
return string(buffer, buffer + len);
}
2) you know the maximum buffer size at run-time and before calling the
C function:
Many compilers will actually accept this:
string f(size_t max)
{
char buffer[max];
<as above>
Alternatively, try this:
#include <alloca.h>
string f(size_t max)
{
char* buffer = alloca(max);
<as above>
3. You don't know the buffer size requirements before calling the C
function:
Some C functions (e.g. snprintf() variants), return the untruncated
length even when truncating the result to the caller-provided buffer.
This can then be used by the caller to allocate a bigger buffer. This
two-call approach can still employ stack-based buffers as per 1 or 2
above.
Other C functions may be able to be called multiple times without
compromising their state or the integrity of the result. In this
case, if the returned length shows the buffer is full and you're not
sure whether it's truncated, you may have to allocate a bigger buffer
and recall the function just in case.
Note: no heap allocation.
Tony
--
[ See http://www.gotw.ca/resources/clcm.htm
for info about ]
[ comp.lang.c++.moderated. First time posters: Do this! ]


|