Rcpp module c++ object finalizer - rcpp

Why this Rcpp module exposed c++ class doesn't compile when specifying object finalizer? Can you provide a working version?
class Exposed{
public:
Exposed(){
printf("constructor has been called\n");
}
private:
int some_field;
}
from Rcpp Modules tutorial:
The .finalizer member function of class_ can be used to register a finalizer. A finalizer is a free function that takes a pointer to the target class and return void. The finalizer is called before the destructor and so operates on a valid object of the target class. It can be used to perform operations, releasing resources, etc ... The finalizer is called automatically when the R object that encapsulates the C++ object is garbage collected.
static void finalizer_of_exposed( Exposed* ptr ){
printf("finalizer has been called\n");
}
RCPP_MODULE(yada){
class_<Exposed>("exposed")
.constructor("")
.finalizer( &finalizer_of_exposed )
;
}

Did you try it as a void function without static ?
Edit 21-Jul-2012: You found a bug! Line 720 of Module.h needs to change:
Index: inst/include/Rcpp/Module.h
===================================================================
--- inst/include/Rcpp/Module.h (revision 3697)
+++ inst/include/Rcpp/Module.h (working copy)
## -717,7 +717,7 ##
private:
void SetFinalizer( finalizer_class* f ){
- if( class_pointer->finalizer_pointer ) delete class_pointer->finalizer ;
+ if( class_pointer->finalizer_pointer ) delete class_pointer->finalizer_pointer ;
class_pointer->finalizer_pointer = f ;
}
and I just fixed that in SVN. Thanks!

Related

Rcpp modules: Returning a reference to a member variable c++ object to R

I have a C++ class that stores a raw pointer to an objects of its own kind as a member variable. The class is exposed via Rcpp modules to R. I would like to return a reference to the member variable via a property. However, it seems that a copy is returned.
This also applies to other cases where different member variable objects are returned to R.
Minimal reproducible example
I create a new skeleton package using Rcpp::Rcpp.package.skeleton('testmod', module = TRUE) and added my own class Foo, exposing it to R. The example can be found here on github.
Content of src/Foo.cpp:
#include <Rcpp.h>
class Foo;
RCPP_EXPOSED_CLASS(Foo)
class Foo
{
public:
Foo():
ancestor_ptr(NULL){}
Foo(const Foo& ancestor):
ancestor_ptr(&ancestor){}
const Foo& get_ancestor() {return *ancestor_ptr;}
const Foo* ancestor_ptr;
};
RCPP_MODULE(mymodule){
using namespace Rcpp ;
class_<Foo>("Foo")
.default_constructor()
.constructor<const Foo&>()
.property("ancestor", &Foo::get_ancestor)
;
}
Testing in an R session gives me:
>library(testmod)
>a <- new(Foo)
>b <- new(Foo, a)
>a
C++ object <0x1c57108> of class 'Foo' <0x22d78b0>
>b$ancestor
C++ object <0x1f8ffa0> of class 'Foo' <0x22d78b0>
So 0x1c57108 != 0x1f8ffa0, and I checked with helper functions not shown that 0x1c57108 is actually the address of object a.
EDIT
I just checked with the help of a uuid member variable and a custom copy constructor that actually copies of the member objects are being made.
What happens is that modules can't really handle returning references, so when calling get_ancestor a copy is being made.
Consider this expanded version of your code:
#include <Rcpp.h>
class Foo;
RCPP_EXPOSED_CLASS(Foo)
class Foo
{
public:
Foo():
ancestor_ptr(NULL){}
Foo(const Foo& ancestor):
ancestor_ptr(&ancestor)
{
Rprintf( "Foo(const Foo&)\n") ;
}
const Foo& get_ancestor() {return *ancestor_ptr;}
const Foo* ancestor_ptr;
void print_ptr(){
Rprintf( "ptr = %p\n", this ) ;
}
void print_ancestor_ptr(){
Rprintf( "ptr = %p\n", ancestor_ptr ) ;
}
};
RCPP_MODULE(mymodule){
using namespace Rcpp ;
class_<Foo>("Foo")
.default_constructor()
.constructor<const Foo&>()
.property("ancestor", &Foo::get_ancestor)
.method( "print_ptr", &Foo::print_ptr )
.method( "print_ancestor_ptr", &Foo::print_ancestor_ptr )
;
}
A copy is made when you invoke the copy constructor, which is fine and what you mean to happen:
> a <- new( Foo )
> b <- new( Foo, a )
Foo(const Foo&)
But one is also made when you call get_ancestor :
> b$ancestor
Foo(const Foo&)
C++ object <0x10204ee00> of class 'Foo' <0x10207c7c0>
However, in b you indeed store the correct pointer:
> a$print_ptr()
ptr = 0x113278820
> b$print_ancestor_ptr()
ptr = 0x113278820

Why does this code crash when ran?

I am making an application for xbox 360 that will import functions which were exported from a system dll and call them when needed. I thought I did everything right as far as exporting then importing the functions, but it crashes on a single line of code.
I started by defining the functions inside of the system dll as follows:
void (__cdecl *SV_GameSendServerCommand)(int Client, int Type, char *Command) = (void(__cdecl * )(int, int, char * ))0x82254940;
bool (__cdecl *Dvar_GetBool)(char *Dvar) = (bool(__cdecl * )(char * ))0x8229EF58;
I created a .def file to export the functions while assigning their ordinals:
LIBRARY testdll
EXPORTS
SV_GameSendServerCommand #1
Dvar_GetBool #2
I built the system dll and placed the resulting testdll.lib in the folder where my application's source code was. I then placed the following in stdafx.h of that application:
#pragma comment(lib, "testdll.lib")
I prototyped the functions to be imported and used a function called resolveFunct to get the addresses of the imported functions.
void (__cdecl *SV_GameSendServerCommand)(int Client, int Type, char *Command);
bool (__cdecl *Dvar_GetBool)(char *Dvar);
UINT32 resolveFunct(char* modname, UINT32 ord)
{
UINT32 ret=0, ptr2=0;
HANDLE ptr32 = 0;
ret = XexGetModuleHandle(modname, &ptr32);
if(ret == 0)
{
ret = XexGetProcedureAddress(ptr32, ord, &ptr2);
if(ptr2 != 0)
return ptr2;
}
return 0; // function not found
}
When I tried printing the address of the function, it was successful and read 0x91F8BF54. I did this twice, and it printed both times. The proceeding line of code caused my application to crash.
DWORD WINAPI Start(LPVOID)
{
for(;;)
{
if(!LoadedUp)
{
printf("0x%p\n", resolveFunct("testdll.xex",2));
if(Dvar_GetBool == NULL)
{
printf("0x%p\n", resolveFunct("testdll.xex",2));
Dvar_GetBool = (bool(__cdecl*)(char*))resolveFunct("testdll.xex",2);
I don't understand why this line of code causes my program to crash, though. Any answers/suggestions are appreciated. Thanks!

Why console app hangs when using a shared dll that containg static variable that use mutex?

I have a shared dll library that contains a class as below :
inside A.dll >> Header File :
class API ErrorHandler
{
public:
ErrorHandler();
virtual ~ErrorHandler();
protected:
static ErrorHandler* defaultHandler();
private:
static ErrorHandler* _pHandler;
static std::mutex _mutex;
};
source(.cpp)
ErrorHandler* ErrorHandler::_pHandler = ErrorHandler::defaultHandler();
std::mutex ErrorHandler::_mutex;
ErrorHandler::ErrorHandler()
{
}
ErrorHandler::~ErrorHandler()
{
}
ErrorHandler* ErrorHandler::defaultHandler()
{
static SingletonHolder<ErrorHandler> sh;
return sh.get(); **<<====== here we get hanged** see the declaration of get
}
SingletoneHolder header file
template <class S>
class SingletonHolder
{
public:
SingletonHolder():
_pS(0)
{
}
~SingletonHolder()
{
delete _pS;
}
S* get()
{
std::lock_guard<std::mutex> lock(_m); <===== cause thread hang
if (!_pS) _pS = new S;
return _pS;
}
private:
S* _pS;
std::mutex _m;
};
After building the above code (every thing related to compiler setting configured correctly) now I want to use it in my console app.
After running console app, app hangs and never reach to main function.
Why std::lock_guard<std::mutex> lock(_m); hangs and prevent main thread to continue executing?
What is alternative?
I am using VS2013 Update5.
content of main file :
#include "ErrorHandler" <== when remove this include app run correctly
#include <iostream>
int main()
{
getchar();
return 0;
}
First, you should post exact contents of the main - with an empty main everything works. Things go south when the ErrorHandler class is being instantiated inside main.
Second, the initialization of your static members occurs inside __DllMainCRTStartup and as stated in the SO question I marked as duplicate, MSDN states that using synchronization primitives from __DllMainCRTStartup can cause a deadlock. A possible solution is to switch to a critical secion.

starting std::thread with anonymous class call

I am curious as to how to correctly start a std::thread using an anonymous class call.
With the below code, if my class only having 1 member variable and I call std::thread td(someclass(shared_mutex)); I get a compiler warning of warning
C4930: 'std::thread td(someclass)': prototyped function not called (was a variable definition intended?)
However, if I add a second member variable as below and call it with
std::thread td(someclass(shared_mutex,x));
I get an error with error C2064: term does not evaluate to a function taking 0 arguments.
class someclass
{
private:
std::mutex& shared_mutex;
int x;
public:
someclass(std::mutex& init_mutex, int init_x) :
shared_mutex(init_mutex),
x(init_x)
{}
//...
};
int main()
{
std::mutex shared_mutex;
int x = 10;
std::thread td(someclass(shared_mutex,x));
td.join();
return 0;
}
The only way around this is by creating an
void operator()()
{}
within the class, but is that the correct method, just to have some kind of starting function for the thread reference or am I missing some other point here? I thought the constructor would be resolver for that?
Try using { and } syntax to construct your object to avoid veximg parses as a function declaration.
std::thread td(someclass(shared_mutex,x))
becomes
std::thread td{someclass{shared_mutex,x}}
It seems that you want your thread to execute the long-running constructor of someclass and then immediately discard the newly constructed someclass. This can be done by passing the thread constructor a function object that does just that:
int main()
{
std::mutex shared_mutex;
int x = 10;
std::thread td([&]{someclass(shared_mutex,x);});
td.join();
return 0;
}
Be warned: constructing a new thread is a hugely expensive operation, so you should avoid casually spawning new threads if you have the ability to instead reuse existing threads, unless you are only going to create new threads very infrequently.

Boost library and CreateThread win API

I have a class such as :
class MyStreamReader
{
public:
MyStreamReader(MyPramameter myPram) {.....}
~MyStreamReader() {}
DWORD WINAPI ReaderThread(LPVOID *lpdwThreadParam )
{
//....
}
};
and i want to call ReaderThread with WinAPI CreateThread. But CreateThread wants ReaderThread function wants a static function.
In some forms it is said that this is possible with boost library such as :
CreateThread(NULL, 0, boost::bind(&MyStreamReader::ReaderThread,this),
(void*)&myParameterObject), 0, NULL);
But i got compilation error:
'CreateThread' : cannot convert parameter x from 'boost::_bi::bind_t<R,F,L>'
to 'LPTHREAD_START_ROUTINE'
So as a result my questions:
Is it possible to call non-static function of a class from
CreateThread using boost lib(or any other method)
If not any C++ THREADing librray you may recomend(for visual C++) which i can call-run non static member function of a class as a thread?
Best Wishes
Update:
So first question: It seesm that it is impossible to call non-static c++ member function from CreateThread win API...
So any recomandations for C++ Multithreading lib whic is possible to call non-static functions as threads...
Update 2:
Well i try boost thread lib...seems it works...
MyStreamReader* streamReader = new MyStreamReader(myParameters);
boost::thread GetStreamsThread
( boost::bind( &MyStreamReader::ReaderThread, streamReader ) );
or (no need for bind)
boost::thread GetStreamsThread(&MyStreamReader::ReaderThread, streamReader);
AND in order to use boost::thread i update my class definition as:
class MyStreamReader
{
public:
MyStreamReader(MyPramameter myPram) {.....}
~MyStreamReader() {}
void ReaderThread()
{
//....
}
};
One common answer to this is to use a static "thunk":
class Worker
{
public :
static DWORD Thunk(void *pv)
{
Worker *pThis = static_cast<Worker*>(pv);
return pThis->DoWork();
}
DWORD DoWork() { ... }
};
...
int main()
{
Worker worker;
CreateThread(NULL, 0, &Worker::Thunk, &worker);
}
You can, of course, pack more parameters into your call to pv. Just have your thunk sort them out correctly.
To answer your question more directly, boost::bind doesn't work with the Winapi that way. I would advise using boost::thread instead, which does work with boost::bind (or, if you have a C++0x compiler, use std::thread with std::bind).

Resources