Skip to content

Instantly share code, notes, and snippets.

@taliesinb
Created March 17, 2016 05:47
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save taliesinb/a3385002601421b3e8e2 to your computer and use it in GitHub Desktop.
Save taliesinb/a3385002601421b3e8e2 to your computer and use it in GitHub Desktop.
Allows LibraryLink projects to call MLPrintf to print straight to a Mathematica notebook, using ordinary printf formatting. Super useful to debug LibraryLink projects live while working with them.
#include <cstdarg>
#include <stdio.h>
#include <stdarg.h>
WolframLibraryData logLibData = NULL;
void MLPrintString(const char* str) {
if (!logLibData) return;
MLINK link = logLibData->getWSLINK(logLibData);
MLPutFunction(link, "EvaluatePacket", 1);
MLPutFunction(link, "CellPrint", 1);
MLPutFunction(link, "Cell", 4);
MLPutString(link, str);
MLPutString(link, "Print");
MLPutFunction(link, "Rule", 2);
MLPutSymbol(link, "CellLabel");
MLPutString(link, "LibraryLink");
MLPutFunction(link, "Rule", 2);
MLPutSymbol(link, "ShowCellLabel");
MLPutString(link, "True");
logLibData->processWSLINK(link);
auto pkt = MLNextPacket(link);
if (pkt == RETURNPKT) {
MLNewPacket(link);
}
}
void MLPrintf(const char *fmt, ...) {
if (!logLibData) return;
va_list args;
va_start(args, fmt);
char buffer[8192];
vsnprintf(buffer, sizeof(buffer), fmt, args);
MLPrintString(buffer);
va_end(args);
}
void EnableLogging(WolframLibraryData libData) {
logLibData = libData;
}
void DisableLogging() {
logLibData = NULL;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment