To overcome the impossibility of giving C library a callback to C++ member function, wanted to implement something like this:
SomeObject* findSomeObjectByHandlePointer(datahandle *dh) { }..
by using a map, which contains addresses of *datahandle as an index, and addresses of *SomeObject’s as value.
When SomeObject is created, it produces a group of datahandle’s, which are unique for the object. Then, it passes a pointer to *datahandle and static callback function to C library, then C library calls back and returns a pointer to datahandle, that in turn can be associated back with a SomeObject.
Which types can you recommend for storing pointer values in a map besides safe but slow <string, SomeObject*>?
This answer tells me to avoid using auto_ptr too.
Normally, C-like callbacks take a
void* user_dataparameter, which allows you to pass in anything you want:Now, simply make the following static member function:
Edit: According to @Martin’s comment, you may get unlucky with a static member function. Better use an
extern "C"function:extern “C” void c_callback(void* my_data){
// same as static method
}
And pass that + your
Ainstance to thatc_func:Or if that
Ainstance needs to outlive the current scope, you need to somehow save the heap-allocated pointer somewhere and delete it manually later on. Ashared_ptror the likes won’t work here, sadly. 🙁On your problem of storing pointer in a map, that’s not a problem at all, see this little example on Ideone.