stdio - How to intercept printf() in c++ code? -
i'm using static library produces std output using printf(). how can intercept in order show output in app , highlighting example?
i have sources of lib , can modify if needed.
i have sources of lib , can modify if needed.
well, if you're sure they're using printf
, , can build code, can utilize against them long don't have other places in there utilize printf
.
(i'm assuming unix-like platform, there might need modification work elsewhere.)
one thing can redefine printf
point own version. write own printf
, link in before standard libraries. neither of these routes you'd consider recommended practice, though should work. neither route requires modification of source of library.
here mess compiler's concept of printf
telling it's different function. add together makefile:
cflags += -dprintf=redirected_printf cxxflags += -dprintf=redirected_printf
(some build systems utilize variable defines
purpose; ymmv.)
this tells compiler replace every instance of identifier printf
redirected_printf
. it's same if set #define printf redirected_printf
@ top of every source file.
now need write redirected_printf
function. prefer pass formatting off function in stdio, vasprintf
, same thing printf
except takes va_list
instead of ...
, returns pointer heap-allocated string output.
#include <stdarg.h> #include <stdio.h> extern "c" int redirected_printf(const char * format, ...) { // create formatted string. char* outstr = 0; va_list ap; va_start(ap, format); int result = vasprintf(&outstr, format, ap); va_end(ap); if(result < 0) // error occurred , `outstr` undefined if result < 0. homecoming result; // string in `outstr` here, display in dialog. // clean , return. free(outstr); homecoming result; }
replacing printf this bit trickier, because have write function named printf
works replacement_printf
above, , have convince linker link version instead of standard library's. might able stick printf
in 1 of compilation units , done it; when clinker links library you're redirecting sources, find printf , link it; later when sees 1 in standard library, drop because @ point nil calls it.
if doesn't work, can seek set printf
library of own ar
, ranlib
commands, link library after 1 you're redirecting.
note if library you're trying redirect shared library (like dll or .so file), won't work; linked standard printf
when built.
this route has lot more caveats , depends on how linker works , bunch of other things, don't recommend it, i'm including here completeness.
c++ stdio
No comments:
Post a Comment