I am trying to call a class member function like a normal C function with the help of boost, but my efforts into looking how to do it just fail so I had come up with something on my own, something that sounds intuitive... I think.
But the problem is that it just keeps crashing when calling the pointers to the boost::function
- fooA
and fooB
.
To do some tests on it:
#include <boost/bind.hpp>
#include <boost/function.hpp>
class MyOtherClass{
public:
MyOtherClass(){}
};
class MyClass
{
std::string name;
public:
void MyFunction(MyOtherClass *data)
{
std::cout << "NAME:" << name << std::endl;
}
boost::function<void(MyOtherClass *)> bindMyFunction;
MyClass(std::string _name)
: name(_name)
{
bindMyFunction = std::bind1st(std::mem_fun(&MyClass::MyFunction), this);
}
};
I then execute the code just once in a main to try it, I expect to see NAME:a\nNAME:b\n
three times but it just crashes after two times:
int main()
{
MyClass a("a");
MyClass b("b");
MyOtherClass c;
//make sure we can save the Class::bindMyFunction variable
void ** someTestA = (void**)&a.bindMyFunction;
void ** someTestB = (void**)&b.bindMyFunction;
//'convert' it to the needed type, just like function-pointers work
//The library uses this below
// Now the correct assignment is the hard part
void(*fooA)(MyOtherClass*) = (void(*)(MyOtherClass*))(*someTestA);
void(*fooB)(MyOtherClass*) = (void(*)(MyOtherClass*))(*someTestB);
//Works
a.MyFunction(&c);
b.MyFunction(&c);
//Works
a.bindMyFunction(&c);
b.bindMyFunction(&c);
//execute the boost::function by calling it like a function
//Crash
fooA(&c);
fooB(&c);
return 0;
}
To my unfortunate luck, I use a library which only accepts a parameter void(*)(MyOtherClass*)
, but I need to encapsulate it in a class. The library uses Callbacks to notify of any changes. So I need to figure a way to convert boost::function<void(*)(MyOtherClass*)>
to a void(*)(MyOtherClass*)
type and then let the library be able to just call(parameters)
it.
But this seems rather a very hard task to accomplish. Are there any approaches to do this the correct way?
Edit: As per request I will make this question more specific, but I am worrying about the question being too localized in this way, but here it goes:
I am trying to make a class which has RakNet encapsulated in it. Put everything in the class (even the RakNet callbacks). Each object instance of that class will be an own client which will connect to a game server:
class MyClass
{
RakClientInterface* pRakClient;
void MyFunction(RPCParameters *pParams){}
boost::function<void(RPCParameters *)> bindMyFunction;
public:
MyClass()
{
pRakClient = RakNetworkFactory::GetRakClientInterface();
if (pRakClient == NULL)
return;
bindMyFunction = std::bind1st(std::mem_fun(&MyClass::MyFunction), this);
//void RakClient::RegisterAsRemoteProcedureCall( int* uniqueID, void ( *functionPointer ) ( RPCParameters *rpcParms ) )
pRakClient->RegisterAsRemoteProcedureCall(&RPC_ServerJoin, /*<need to pass boost::function here somehow>*/);
}
};