如何在运行时创建一个mex函数printf?

我有一个在我的MATLAB脚本中调用的mex文件。 mex函数可能需要一段时间才能运行,因此为了防止我的代码“在没有任何输出的情况下停在那里”,我在mex文件中放入了许多printf语句来输出有关正在处理的数据的一些运行信息。

但是当我调用mex函数时,它不会printf任何东西并且在int运行期间保持不变。 最后,在完成其工作后,它将printf出我想要的所有信息 – 不是在运行时,而是完成之后 。 这不是我想要的。

所以我想知道如何使printf成为我想要的东西,而且在我想要的时候也是printf

是的, mexPrintf就是您所需要的。 但请注意,命令窗口不会强制刷新它使用的缓冲区,通常会在打印消息之前导致很长的延迟。 如果在调用mexPrintf后开始繁重的计算,就会发生这种情况。

解决方法是使用

 mexEvalString("drawnow;") 

每次打电话给mexPrintf

如果您发现没有吸引力,可以创建一个调用两个的宏:

 #define printfFnc(...) { mexPrintf(__VA_ARGS__); mexEvalString("drawnow;");} 

这使用了可变参数宏__VA_ARGS__ 。 它可能不是标准的一部分,但似乎是在GCC和Visual C ++中。 只需调用printfFnc就像调用printf (或mexPrintf )一样。

有一个未记录的C ++函数驻留在libmwservices.dll 。 它显然会刷新输出缓冲区。 这是一个例子:

test_mex_print.cpp

 #include "mex.h" #pragma comment(lib, "libmwservices.lib") extern bool ioFlush(void); void mexFunction(int nlhs, mxArray *plhs[], int nrhs, const mxArray *prhs[]) { for(int i=0; i<100000; i++) { mexPrintf("%d\n", i); ioFlush(); } } 

只需将其编译为: mex -largeArrayDims test_mex_print.cpp

你可以使用mexPrintf

 * * mex equivalent to MATLAB's "disp" function */ extern int mexPrintf(const char *fmt, /* printf style format */ ... /* any additional arguments */); 

我有与OP相同的问题,其中mexPrintf()在mex文件完成运行之前不会打印任何输出。 而且,mexEvalString(“drawnow;”); 似乎没有解决问题,或者至少它没有我的设置(MATLAB2015b与C ++ 11 MEX代码的64位MinGW编译器)。

但是,使用mexEvalString(“pause(.001);”); 在mexPrintf()之后确实修复了它。 我花了一些试错才弄清楚,所以我希望这可能对将来的参考有用。

TLDR:使用mexEvalString(“pause(.001);”);

printf打印到stdout,这不是 matlab屏幕。 (默认隐藏,最后收集/显示)

试试mexprintf():

http://www.mathworks.co.uk/help/matlab/apiref/mexprintf.html

在C MEX文件中,您必须调用mexPrintf而不是printf来显示字符串。

 C Syntax #include "mex.h" int mexPrintf(const char *message, ...); Arguments message String to display. In C, the string can include conversion specifications, used by the ANSI® C printf function. ... In C, any arguments used in the message. Each argument must have a corresponding conversion specification. Returns Number of characters printed including characters specified with backslash codes, such as \n and \b.