[Rcpp-devel] Wrapping a C struct in C++ for constructor/destructor

Romain Francois romain at r-enthusiasts.com
Fri Dec 14 17:43:05 CET 2012


I would create a class that contains a pointer to the c struct. 

This obviously leaves the problem of freeing the memory, i.e does the c++ object own the pointer. 

Maybe a strategy using some reference counting smart pointer. 

In RcppEigen we have not resolved this, we simply exposed a free methid for the class and the programmer has to call it. Not the best strategy perhaps. 


You could also prevent copy ctor and assignment op by making them private without an implementation, and always pass them by reference. Then you can consider that your c++ object owns the pointer. 





Le 14 déc. 2012 à 17:10, Douglas Bates <bates at stat.wisc.edu> a écrit :

> This is more a C++ question than an Rcpp question although, of course, the application will be through Rcpp.
> 
> I want to use C functions defined in the CHOLMOD package using Rcpp.  The arguments to these functions and the returned values are usually pointers to C structs. There are several such structs defined in CHOLMOD and it gets tedious to use code that allocates storage for the struct, populates the struct, uses it and then frees it.  (If you look in the Matrix package sources you will see several inelegant utility functions and macros to perform these operations).
> 
> For an Rcpp/C++ approach I would prefer to use constructors and destructors for the memory allocation and freeing.  Is the recommended approach to create a C++ class or struct that extends the C struct or to create a C++ class with the C struct as a member of the class?
> 
> I should be able to create the code for myself if I just know where to look for examples.  I tried StackOverflow but I was unable to narrow down my search.  Pointers to sections of "C++ Annotations" or to StackOverflow questions would be appreciated.
> _______________________________________________
> Rcpp-devel mailing list
> Rcpp-devel at lists.r-forge.r-project.org
> https://lists.r-forge.r-project.org/cgi-bin/mailman/listinfo/rcpp-devel


More information about the Rcpp-devel mailing list