[Rd] Using STL containers in R/C++

Paul Roebuck roebuck at mdanderson.org
Fri Jan 6 15:38:29 CET 2006


On Thu, 5 Jan 2006, Dominick Samperi wrote:

> Dirk Eddelbuettel wrote:
>
>> Dominick Samperi wrote a Rcpp.{hpp,cpp} class for
>> C++ to R interface that is used in RQuantLib. Dominick
>> was musing about releasing this stand-alone to CRAN
>> as well, but I don't think it has happened.
>
> It just happened. I uploaded Rcpp to CRAN today. The
> package contains a  PDF file Rcpp.pdf that describes
> the package and the class library.

It seems to me from looking at page 4 of your PDF that
your error handling is still incomplete. Calling error()
from within the catch handler will invoke a setjmp() and
the exception object's memory will not be reclaimed.

The code I wrote for C++ was basically similar except
that it copied the exception string into R temporary memory
allocated in the catch handler. Thus the exception object
will have been destroyed prior to invocation of error()
and R's garbage collection will take care of the rest
after the error message is printed.


SEXP do_something(SEXP vntObj1, SEXP vntObj2, SEXP vntObj3)
{
    unsigned n = 0;
    // Do PROTECT() stuff, incrementing n after each

    // Extract protected object info to C/C++ pointer variables

    bool fError = false;
    char* szDetail = NULL;

    try
    {
        // Make C++ calls that perform procedure logic
    }
    catch (const std::exception& e)
    {
        const char* const szMsg = e.what();
        void* rheap = R_alloc(std::strlen(szMsg)+1, sizeof(char));
        szDetail = static_cast<char*>(rheap);
        std::strcpy(szDetail, szMsg);
        fError = true;
    }
    catch (...)
    {
        const char* const szMsg = "unhandled exception";
        void* rheap = R_alloc(std::strlen(szMsg)+1, sizeof(char));
        szDetail = static_cast<char*>(rheap);
        std::strcpy(szDetail, szMsg);
        fError = true;
    }

    if (fError)
    {
        Rf_error(szDetail);
        /*NOTREACHED*/
    }

    UNPROTECT(n);

    return NULL_USER_OBJECT;
}


----------------------------------------------------------
SIGSIG -- signature too long (core dumped)



More information about the R-devel mailing list