Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to redirect STDOUT from a dll

Tags:

c++

c

I have a dll file that writes to STDOUT via std::cout.

Is there anyway to redirect the output from the dll to the application that is using it, without having to create functionality inside the dll? For example is there anyway to "listen" to its output?

I'm looking for an answer that will work cross-platform.

like image 575
Soapy Avatar asked Sep 10 '25 14:09

Soapy


2 Answers

A DLL is not a separate process but a dynamic library that's loaded into your application address space. That means, when the DLL calls printf or whatever output into the stdout/stderr handlers, will inherit the stdout/stderr handles or your running application and will behave indeed as you put printf inside your application. If you want to capture the output of what's called from a DLL, you need to run it from a proxy EXE, that calls your DLL function. In that way, you can just redirect the stdout/stderr pipes to your process and do whatever you want.

By the way, in my opinion, this would be a totally wrong approach. If you use a DLL, you should have some sort of return codes from its function and not relay on its output on stdout.

like image 96
Leonardo Bernardini Avatar answered Sep 13 '25 02:09

Leonardo Bernardini


Regarding the cross-platform requirement, forget about it. When you throw in windows with:

  • the console/gui option
  • potentially different libc (msvcrt) linked by dll and host application
  • 3 different methods depending on the stdio layer used

I will focus on windows, since I expect this stuff to be easier on Unix (just redirect the host application stdout/stderr).

First of all make sure that the same msvcrt is linked by the host application and the DLL. 'stdout' means different objects if you load different msvcrt instances (i.e. host app links debug msvcrt and DLL links release msvcrt).

The above link details the different methods you may want to use (and combine) depending on the DLL.

like image 25
Giuseppe Corbelli Avatar answered Sep 13 '25 03:09

Giuseppe Corbelli