How can I capture stdout of a generic shared library method called from MATLAB?

조회 수: 11 (최근 30일)
I have written C-code that uses cout, cerr, printf, or fprintf. I am calling this as part of a C-shared library (DLL) via LOADLIBRARY and CALLLIB. I am unable to view the output when it is called from MATLAB on a Windows platform.

채택된 답변

MathWorks Support Team
MathWorks Support Team 2015년 6월 15일
Anything printed to standard output (stdout) or standard error (stderr) is lost when a Windows program is running without a console.
To work around this issue, you can open a new console window to display anything that is sent to stdout or stderr. This solution makes use of the AllocConsole function, about which more information is available on the following page:
https://msdn.microsoft.com/en-us/library/windows/desktop/ms681944%28v=vs.85%29.aspx
Add a method to your shared library that includes the following lines of code:
if (AllocConsole()==0) {
freopen("CONOUT$", "w", stdout);
freopen("CONOUT$", "w", stderr);
}
Also be sure to include the following header:
#include <Windows.h>
Then either have the method called in a static initializer of your library, or call this method prior to calling any other method within that library. By calling this method first, the console exists globally and all other methods from that library will make use of it.
  댓글 수: 2
Philip Borghesani
Philip Borghesani 2016년 7월 28일
If the library is linked with (built with?) the same or a compatible version of the Microsoft C run-time libraries as MATLAB then you should not need this fix and stdout should be automatically redirected to MATLAB.
A.B.
A.B. 2020년 4월 16일
편집: A.B. 2020년 4월 16일
I am having the same problem on macOS. Is there a solution for macOS?

댓글을 달려면 로그인하십시오.

추가 답변 (0개)

카테고리

Help CenterFile Exchange에서 C Shared Library Integration에 대해 자세히 알아보기

제품

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!

Translated by