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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With