Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

R extension in C: how to link a struct to a SEXP pointer?

I'm currently writing a C extension for R. I would like to create a struct linked to an existing SEXP pointer. For example:

struct MyData {
    SEXP exp;
    int i;
}

SEXP create(SEXP p1)
{
    struct MyData p* = malloc(sizeof(MyData));
    p->exp =  p1;
    p->i = 1234;
    SEXP ext = PROTECT(R_MakeExternalPtr(p, R_NilValue,R_NilValue));
    R_RegisterCFinalizerEx(ext,myFinalizer, TRUE);
    UNPROTECT(1);
    return ext;
}

void myFinalizer(SEXP x)
{
    void * p = R_ExternalPtrAddr(handle);
    free(p);
}

How to correctly handle the p->exp pointer? How to tell the garbage manager that I'm using a SEXP data? How should I protect/unprotect this SEXP data?

Thank you for your help.

like image 554
Pierre Avatar asked Oct 20 '25 16:10

Pierre


1 Answers

I think I answered my problem instead of wrapping a

struct MyData {
    SEXP exp;
    int i;
}

I create a vector:

SEXP ext = PROTECT(allocVector(VECSXP, 2));nprotect++;
SET_VECTOR_ELT(ext, 0, exp);
SET_VECTOR_ELT(ext, 1, sexpI);

and ext is my object and I let the R garbage manager to manage it. But the structure is not opaque and the user can modifiy it.

like image 96
Pierre Avatar answered Oct 23 '25 06:10

Pierre