简体   繁体   中英

Linking C library to R

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.

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 -cr r-essentials m2w64-toolchain posix

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

It is not going to be elegant, but if nobody found an elegant solution for 4 years, you might aswell use:

shell("cc test.c -o test -lxlsxwriter -lz")

This is going to help with this part as well as with any minor need to istantly access xlsx functionality

At this point I am just trying to get the hello-world example to run from R.

You probably knew this already, but just in case you didn't think of using the shell() command.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM