简体   繁体   中英

How R extracts function definitions in a dynamic library

When there is a function defined in source.c like

#include <R.h>
#include <Rdefines.h>

SEXP myfunc (SEXP n1, SEXP n2){
    SEXP mysum_sexp;
    PROTECT(mysum_sexp = NEW_NUMERIC(1));
    PROTECT(n1);
    PROTECT(n2);
    NUMERIC_POINTER(mysum_sexp)[0] = NUMERIC_POINTER(n1)[0] 
                                   + NUMERIC_POINTER(n2)[0];
    UNPROTECT(3);
    return(mysum_sexp);
}

and the source.c file is compiled using

R CMD SHLIB source.c

a dynamic (shared) library is created with default name source.so . After the compiling process, when we type in R

> dyn.load("source.so")

the function in the compiled code can be called using as

> .Call("myfunc", 4, 7)

and the result is 11 as expected. How R passes the arguments to the foreign function without knowing the definition of the function? Is the calling process blank or does R follow standard definitions with n arguments in type of SEXP for n = 1, 2, ..., n1 ?

I know using the .Call interface without Rcpp is old fashioned but I want to learn the mechanism behind it.

Thanks in advance.

Thanks to MrFlick , he sent me the link of the source of dotcode.c and this peace of code explains my question:

switch (nargs) {
case 0:
  retval = (SEXP)ofun();
  break;
case 1:
  retval = (SEXP)fun(cargs[0]);
  break;
case 2:
  retval = (SEXP)fun(cargs[0], cargs[1]);
  break;
case 3:
  retval = (SEXP)fun(cargs[0], cargs[1], cargs[2]);
  break;
case 4:
  retval = (SEXP)fun(cargs[0], cargs[1], cargs[2], cargs[3]);
  break;
case 5:
  .
  .
  .
case 65:
.
.
default:
}

It seems R looks at the number of arguments and follows a standard definition which takes several numbers (or none) of SEXP arguments at runtime. The maximum number of arguments allowed is 65 . It is known that all of the functions return a SEXP. Situations are hand coded. That proves that the foreign function calling is blank, in other words, number of entered arguments directly determines the function definition.

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