Brandon Hilton
Brandon Hilton

Reputation: 51

How to call a c++ function using c && redirect application output to textEdit in Qt

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?

Upvotes: 1

Views: 949

Answers (5)

Kamil Klimek
Kamil Klimek

Reputation: 13130

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

Upvotes: 0

Adam W
Adam W

Reputation: 3698

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.

Upvotes: 0

Amardeep AC9MF
Amardeep AC9MF

Reputation: 19044

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.

Upvotes: 1

Michael Aaron Safyan
Michael Aaron Safyan

Reputation: 95499

If 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.

Upvotes: 2

Related Questions