#include #include #include // in addition to the usuals: #include #include #include #include #include SEXP myfunction(SEXP a, SEXP b){ a=PROTECT(a); b=PROTECT(b); // creating pointers to input arguments int * a_val = INTEGER(a); double * b_val = REAL(b); // accessing the input arguments: printf("a = %d and b[0] = %f\n", *a_val, b_val[0]); // allocating memory for the new array,with length *a: SEXP newobject1 = PROTECT(allocVector(REALSXP, (*a_val))); //creating C pointer to the new array: double * newarray = REAL(newobject1); // allocating memory for a double: SEXP newobject2 = PROTECT(allocVector(REALSXP, 1)); //creating C pointer to the new double: double * newdouble = REAL(newobject2); // the new array should contain the square roots of the array b_val int i=0; *newdouble=0.0; // the code: for(i=0;i<(*a_val);i++){ newarray[i] = sqrt(b_val[i]); if(newarray[i]>*newdouble){ *newdouble = newarray[i]; } } // creating a list to hold the two return values. SEXP ret = PROTECT(allocVector(VECSXP, 2)); //the list to be returned in R //inserting the desired objects into the list (or at least pointers to them): SET_VECTOR_ELT(ret, 0, newobject1); SET_VECTOR_ELT(ret, 1, newobject2); // creating list of names/titles to be returned in the output list SEXP names = PROTECT(allocVector(STRSXP, 2)); SET_STRING_ELT(names, 0, mkChar("the_new_array")); SET_STRING_ELT(names, 1, mkChar("the_new_double")); setAttrib(ret, R_NamesSymbol, names); UNPROTECT(6); return ret; } SEXP myfunction_silent(SEXP a, SEXP b){ a=PROTECT(a); b=PROTECT(b); // creating pointers to input arguments int * a_val = INTEGER(a); double * b_val = REAL(b); // accessing the input arguments: //printf("a = %d and b[0] = %f\n", *a_val, b_val[0]); // allocating memory for the new array,with length *a: SEXP newobject1 = PROTECT(allocVector(REALSXP, (*a_val))); //creating C pointer to the new array: double * newarray = REAL(newobject1); // allocating memory for a double: SEXP newobject2 = PROTECT(allocVector(REALSXP, 1)); //creating C pointer to the new double: double * newdouble = REAL(newobject2); // the new array should contain the square roots of the array b_val int i=0; *newdouble=0.0; // the code: for(i=0;i<(*a_val);i++){ newarray[i] = sqrt(b_val[i]); if(newarray[i]>*newdouble){ *newdouble = newarray[i]; } } // creating a list to hold the two return values. SEXP ret = PROTECT(allocVector(VECSXP, 2)); //the list to be returned in R //inserting the desired objects into the list (or at least pointers to them): SET_VECTOR_ELT(ret, 0, newobject1); SET_VECTOR_ELT(ret, 1, newobject2); // creating list of names/titles to be returned in the output list SEXP names = PROTECT(allocVector(STRSXP, 2)); SET_STRING_ELT(names, 0, mkChar("the_new_array")); SET_STRING_ELT(names, 1, mkChar("the_new_double")); setAttrib(ret, R_NamesSymbol, names); UNPROTECT(6); return ret; }