Linking C library to R

340 Views Asked by At

I recently found this C library (http://libxlsxwriter.github.io/), and attempted to use it with R.

Getting the C library to work by itself was not difficult. I downloaded zlib and libxlsxwriter using msys2, and ran make in the libxlsxwriter folder.

Now I can run this Hello-World example, lets call it test.c:

#include "xlsxwriter.h"
void main() {
  lxw_workbook  *workbook  = workbook_new("myexcel.xlsx");
  lxw_worksheet *worksheet = workbook_add_worksheet(workbook, NULL);
  int row = 0;
  int col = 0;
  worksheet_write_string(worksheet, row, col, "Hello me!", NULL);
  workbook_close(workbook);
}

Now I can compile test.c by running:

cc test.c -o test -lxlsxwriter -lz

And then run the executable:

./test

And now I have a Hello-World excel document.

Getting it to work with R has been much trickier. If I simply run:

R CMD SHLIB test.c

I get this error: ibxlsxwriter/include/xlsxwriter/common.h:19:42: fatal error: xlsxwriter/third_party/queue.h: No such file or directory #include "xlsxwriter/third_party/queue.h"

Yet the file is clearly there when I check.

Any advice on how to connect this C library with R? At this point I am just trying to get the hello-world example to run from R.

Would it be a better approach to start out building a package, with xlsxwriter in the inst folder, and then try to write a makevars that will get xlsxwriter to compile correctly? I know I would have to include PKG_CPPFLAGS = -I../inst/libxlsxwriter but I am guessing I would need more than that.

1

There are 1 best solutions below

0
On

You may want to try Continuum's Anaconda R packages. They use MSYS2 packages fairly directly. The toolchain package is called m2w64-toolchain and the posix package is sometimes useful for building R packages too.

conda install -c r r-essentials m2w64-toolchain posix

Disclaimer: I work for Continuum, but I also work on MSYS2.