PabRvss
PabRvss

Reputation: 9

Can you run C code in R in Windows without losing compatibility?

I'm building a R package from an existing C library using RStudio. I was testing the library in Windows using an Ubuntu terminal with WSL. It mainly uses these two commands:

gcc -x c -o pvalues.so src/main.c -shared -fPIC -pthread -O3 -lm
gcc -x c -o pvalues src/main.c -fPIC -pthread -O3 -lm

The author of the C library told me that works in Linux and Mac, and as far as I'm concerned, I cannot run C code in Windows without WSL or a VM. I'm building the R package using Rcpp, which is oriented to C++ code but it only needs a wrapper to run the C code I need, but here's my question: Will the R package work fine in Windows despite calling C functions?

Also, I was thinking about using .Call instead of Rcpp, but I read that Rcpp is easier to work with. Is it slower than .Call?

I was testing with smaller and simpler C functions using Rcpp and worked fine, but the C library I'm working with uses libraries like stdio.h, stdlib.h, tgmath.h, time.h, ssemathlib and pthread.h, so I don't know if all of them are compatible with Rcpp.

Upvotes: 0

Views: 64

Answers (1)

Andrea Manica
Andrea Manica

Reputation: 321

You have two problems here:

First, if your C code does not run on Windows, you will not be able to call it from R on a Windows machine. If you want to use a C/C++ library in your R code on a given operating system, that library needs to work on that operating system. Most of the libraries you are calling are the standard libraries, and they should be fine on any operating system. But the likely reason why your original code does not work on Windows is that it uses pthreads, which is commonly found in *nix systems. There are some ports on Windows, but I have no experience of them and they are not very often used (nor would I assume them to be a simple drop in replacement, you would probably have to modify your code a bit).

I am afraid that, even if you got your code with pthreads to work on windows, you would then have to consider carefully how to integrate it into R. There is an excellent paper by Dirk Eddelbuettel on how to use an external library with Rcpp https://arxiv.org/abs/1911.06416 That paper breaks down the individual steps in a really clear way; read it carefully as it provides a blueprint for what you are wanting to do. The Rcpp framework is excellent, fast, and highly recommended. But the task you are describing is not a straightforward one (depending on the size of the C code base), and if you have threading, it gets much more complex.

Upvotes: 1

Related Questions