do_fun function wrapper for const char * arguments

Posted by David Haley on Tue 07 Mar 2006 07:53 AM — 1 posts, 4,580 views.

USA #0
While rewriting my code base in C++ and most recently with the move to my shared string library, I've had several occasions where I needed to call a do_fun with a const char * argument. But do_fun is defined as taking a char *.

Instead of changing every single do_fun, and changing every do_fun's dependence on the argument being a char*, I wrote a wrapper that lets you call any do_fun with a const char * argument.
// A wrapper to call a do_function with a constant argument
// -- Ksilyan 2006-mar-07
inline void dofun_wrapper( DO_FUN * fn, Character * ch, const char * argument )
{
    char * buf = new char [ strlen(argument) + 1 ];
    strcpy(buf, argument);
    (*fn) (ch, buf);
    delete [] buf;
}


Why create a block of memory and copy the string into it, instead of just casting the const char * to a char *? Because you don't want there to be any possibility of the original string being edited by the do_fun.

I don't know if this will be useful to anybody, but here it is. It's probably only relevant for moderately experienced coders. I hereby release this to the public domain.