I have char* which is of fixed (known) width but is not null terminated.
I want to pass it into LOG4CPLUS_ERROR("Bad string " << char_pointer); but as its not null terminated it will print it all.
Any suggestions of some light weight way of getting "(char[length])*char_pointer" without performing a copy?
Real
iostreamsWhen you’re writing to a real iostream, then you can just use
ostream.write()which takes achar*and a size for how many bytes to write — no null termination necessary. (In fact, any null characters in the string would be written to the ostream, and would not be used to determine the size.)Logging libraries
In some logging libraries, the stream that you write to is not a real iostream. This is the case in Log4CPP.
However, in Log4CPlus which is what it appears matt is using, the object that you’re writing to is a
std::basic_ostringstream<tchar>(seeloggingmacros.handstreams.hfor the definition, since none of this is obvious from the documentation). There’s just one problem: in the macroLOG4CPLUS_ERROR, the first<<is already built into the macro, so he won’t be able to callLOG4CPLUS_ERROR(.write(char_pointer,length))or anything like that. Unfortunately, I don’t see an easy way around this without deconstructing theLOG4CPLUS_ERRORerror macro and getting into the internals of Log4CPlusSolution
I’m not sure why you’re trying to avoid copying the string at this point, since you can see that there’s a lot of copying going on inside the logging library. Any attempt to avoid that extra string copy is probably unwarranted optimization.
I’m going to assume that it’s an issue of code cleanliness, and maybe an issue of making sure the copy happens inside the
LOG4CPLUS_ERRORmacro, as opposed to outside it. In that case, just use: