I'm trying to do a couple of things at once. I'm trying to do one major thing: redirect the application output that is displayed in the Qt Creator console to a textEdit that I have on my GUI. However, the class that I need to do this in is written in C and all of its related headers are in C as well. Is there a way that I can redirect the output into the textEdit within the C class?
views:
173answers:
5If you can modify the C code, you could allow it to take a callback such that text is sent to the callback function, instead of being merely printed with printf. For example, you could have something like:
void someFunctionInC
(
/* other parameters ... */
void (*printcallback)(const char* text, void* extra_arg),
void* extra_arg
)
{
/* ... */
printcallback("Hello world\n",extra_arg); /* instead of using printf */
/* ... */
}
You could then, in C++, create a callback that casts the void* extra_arg parameter back to a class and invokes a method on that class with the given text. Another possibility is you could use snprintf and create a variant of your C function that will print to a string instead of printing to standard out. Note that these solutions all require you to be able to modify the given C function. If it's absolutely not possible to modify the C function, you could use close, pipe, dup2, etc. to redirect stdout to a pipe and then read back the results from the pipe, but that is a really, really ugly solution. Good luck.
Interfacing C++ and C functions involves working around the name mangling that takes place by default in C++ to support function overloading.
To call a C++ function from a C function you must declare the C++ function with extern "C" qualifier. That instructs the compiler to leave its name unmangled.
To call a C function from a C++ function, you must prototype it with extern "C" in the scope of the C++ function.
This is a bit old, but take a look here. It seems like QTextStream
is the answer, but the specifics I'm not sure about.
QProcess is QIODevice. If you are invoking this C programm, you may use QProcess and read it's output from it with QProcess::readAll* members