How to debug the C code for LibraryLink?

Update: The very likely reason for the garbled error messages is that you have a Chinese version of Visual Studio printing errors in Chinese, and there is a mismatch in the character encoding of these messages and how Mathematica tried to interpret them.


CreateLibrary has two very useful options: "ShellCommandFunction" and "ShellOutputFunction".

Set them both to Print.

The first will print the compiler command line. You will know how Mathematica is invoking the compiler precisely. You can use the same command line in a terminal and compile without Mathematica if you wish.

The second will print the output from the compiler. This usually has much more information about the error than what is shown through the cmperr messages. I always use this option with CreateLibrary because the limited error information shown through the messages just isn't sufficient.


More tips to debug LibraryLink stuff

Terminal output

The first step is to make sure your code compiles. Then you have to make sure it runs correctly. It might crash, and there might be messages in the terminal about the cause of the crash. Or you just might want to see debugging output written to the terminal.

Unfortunately it is not possible to see terminal output when running with the Front End. It often helps if you run the kernel in command line mode (i.e. no front end), because you will be able to see any information output to the terminal.

It is also possible to run the kernel with the front end, yet still attached to a terminal. I wrote a blog post about how to do this on OS X and Windows. It should be possible to use the same ideas on Linux too.

In short: on Windows just set up math.exe to be used as the kernel instead of MathKernel.exe.

Debugging features in LTemplate

I wrote the LTemplate package to simplify working with LibraryLink.

Note 1: I recommend getting comfortable with plain LibraryLink before starting with LTemplate. LTemplate makes LibraryLink easier to use, not easier to learn.

Note 2: LTemplate requires using C++, not C. It is necessary to have at least basic knowledge of C++ (basic understanding of classes, templates, exceptions).

LTemplate has a few features to simplify debugging:

The function mma::print can be used to print directly to the notebook instead of to the terminal, so you can see debugging output with the front end.

There is a streams interface for this: output to mma::mout the same way you would output to std::cout or std:cerr and flush the stream. The output will be Printed in the notebook.

Some C++ libraries, such as Armadillo, can be set up to send their own debugging output to a stream.

There is a massert macro provided, which works like the standard assert macro, but instead of printing to stderr and terminating the kernel process, it prints to the notebook and simply returns from the library function.

LTemplate also catches any runaway C++ exceptions (which may come from a library you use), to prevent a kernel crash in this case. For exceptions derived from std::exception it prints the description.

Finally, LTemplate makes error checking/handling in your library easy: use RAII and when there is a problem just throw an mma::LibraryError exception with a descriptive error message. With good error checking you will be able to avoid problems more often. With descriptive error messages you will be able to find the source of the problems faster.


For me (Windows 10) I get a readable error message like enter image description here

So I add mint saved;. Compiling again I get enter image description here

which leads me to change your MArgument_setReal(Res,tensor_N); to MArgument_setMTensor(Res,tensor_N); and then things work.

BTW: I use

Needs["CCompilerDriver`"];
srccode="
#include \"WolframLibrary.h\"

DLLEXPORT int NonzeroBasis(WolframLibraryData libData, mint Argc, 
                           MArgument *Args, MArgument Res) {
  /*define the argument-varible*/
  mint i, p;
  mreal u;
  MTensor tensor_U;
  mreal *U;
  /*----------------------------*/
  mint j, r;
  mreal saved;
  mreal temp;
  mreal *left, *right, *N;
  MTensor tensor_N;
  mint type = MType_Real;
  mint dims[1];
  mint rank = 1;
  int err;
  /*assign the argument-value to argument-varible*/
  i = MArgument_getInteger(Args[0]);
  p = MArgument_getInteger(Args[1]);
  u = MArgument_getReal(Args[2]);
  tensor_U = MArgument_getMTensor(Args[3]);
  U = libData->MTensor_getRealData(tensor_U);
  dims[0] = p + 1;
  err = libData->MTensor_new(type, rank, dims, &tensor_N );
  N = libData->MTensor_getRealData(tensor_N);
  /*main implementation*/
  N[0] = 1.0;
  for(j = 1; j <= p; j++){
    left[j] = u - U[i+1-j];
    right[j] = U[i+j] - u;
    saved = 0.0;
    for(r = 0; r < j; r++){
        temp = N[r]/(right[r+1] + left[j-r]);
        N[r] = saved + right[r+1]*temp;
        saved = left[j-r]*temp;
    }
    N[j] = saved;
  }
  /*return the result*/
  MArgument_setMTensor(Res,tensor_N);
  return LIBRARY_NO_ERROR; 
}
";
lib = CreateLibrary[srccode, "NonzeroBasis"]
NonzeroBasis =
  LibraryFunctionLoad[lib, "NonzeroBasis",
                      {Integer, Integer, Real, {Real, 1}}, {Real, 1}]

Perhaps you need to define MTensor for variable left and right. The modified code is:

#include "WolframLibrary.h"

DLLEXPORT int NonzeroBasis(WolframLibraryData libData, mint Argc,
                       MArgument *Args, MArgument Res) {
  /*define the argument-varible*/
  mreal saved;
  mint i, p;
  mreal u;
  MTensor tensor_U;
  mreal *U;
  /*----------------------------*/
  mint j, r;
  mreal temp;
  mreal *left, *right, *N;
  MTensor left_t, right_t, tensor_N;
  mint type = MType_Real;
  mint dims[1];
  mint rank = 1;
  int err;
  /*assign the argument-value to argument-varible*/
  i = MArgument_getInteger(Args[0]);
  p = MArgument_getInteger(Args[1]);
  u = MArgument_getReal(Args[2]);
  tensor_U = MArgument_getMTensor(Args[3]);
  U = libData->MTensor_getRealData(tensor_U);
  dims[0] = p + 1;
  err = libData->MTensor_new(type, 1, dims, &tensor_N );
  N = libData->MTensor_getRealData(tensor_N);
  err = libData->MTensor_new(type, 1, dims, &left_t );
  left = libData->MTensor_getRealData(left_t);
  err = libData->MTensor_new(type, 1, dims, &right_t );
  right = libData->MTensor_getRealData(right_t);

  /*main implementation*/
  N[0] = 1.0;
  for(j = 1; j <= p; j++){
      left[j] = u - U[i+1-j];
      right[j] = U[i+j] - u;
      saved = 0.0;
      for(r = 0; r < j; r++){
          temp = N[r]/(right[r+1] + left[j-r]);
          N[r] = saved + right[r+1]*temp;
          saved = left[j-r]*temp;
      }
      N[j] = saved;
  }
  /*return the result*/
  MArgument_setMTensor(Res,tensor_N);
  return LIBRARY_NO_ERROR; 
}

This time it is giving the same results as other functions.

enter image description here