How can i convert pointer-method of some class to pointer-function?
Greating everybody! I have a function-pointer method
int Myclass::*myMethod(char* a,char* b){
//some code
}
And try to run it
bool Myclass::myMethod2(){
AnotherClass *instance = AnotherClass:getInstance();
instance-> addParams(&myMethod);
return true;
}
AnotherClass - this class in another dll. AnotherClass definition
class AnotherClass
{
//friend class Myclass;
public:
static Another开发者_运维百科Class* getInstance();
void addParams(int (*myMethod)(char*, char*) =0);
//I try so void addParams(int (Myclass::*myMethod)(char*, char*) =0);
};
And have error C2664. Cannot convert parameter 1 from 'int Myclass::* (__cdecl *)(char *,char *)' to 'int (__cdecl *)(char *,char *).
Hm.. What should i do?
You can't.
The addParams()
method needs a function that accepts two char*
arguments.
Myclass::myMethod
accepts two char*
arguments and a Myclass
object.
There's no way to make the two compatible.
EDIT: I misread your question slightly, and didn't notice the bit about the DLL - but one and three still applies if you have control over the DLL, and have the desire to modify it. If not, all you can do is number two.
In this case there are three things you could do:
One, change the way your AnotherClass
is designed by declaring addParams
like so:
void addParams(int (Myclass::*)(char*, char*) =0);
Two, you could make Myclass::myMethod()
a static member, and then your original declaration of addParams
would work.
Three, you could use a library like boost to bind the method as follows:
bool Myclass::myMethod2(){
AnotherClass *instance = AnotherClass:getInstance();
instance-> addParams(boost::bind(&Myclass::myMethod, this));
return true;
}
class AnotherClass
{
//...
void addParams(boost::function<int(char*, char*)>);
};
You're invoking the method from inside an instance of an object. (Assuming Myclass::myMethod2() is not static)
You can call the method from this:
instance-> addParams(&(this->myMethod));
精彩评论