Call a member function with bare function pointer - c++

What's the best way to call a member function if you have an object and a bare function pointer pointing to the member? Essentially I want to call the function pointer with thiscall calling convention.
Background: I'm looking up symbols in a shared library dynamically, obtaining a factory function pointer and a pointer to a certain member function I want to call. The member function itself is not virtual. I have no control over the shared library, I just have the binary.
Example:
typedef void * (*GenericFptr)();
GenericFptr lookup(const char *);
class CFoo;
GenericFptr factoryfn(lookup("CFoo factory function"));
CFoo *foo = reinterpret_cast<CFoo *>(factoryfn());
GenericFptr memberfn(lookup("CFoo member function"));
// now invoke memberfn on foo
Currently I'm using an union to convert the function pointer to a pointer to member function. It's ugly and creates dependencies to compiler implementation details:
class CFoo {
public:
void *dummy() { return 0; }
};
typedef void * (CFoo::*FooMemberPtr)();
union {
struct {
// compiler-specific layout for pointer-to-member
void *x, *y;
GenericFptr ptr;
} fnptr;
FooMemberPtr memberfn;
} f;
f.memberfn = &CFoo::dummy; // init pointer-to-member
f.fnptr.ptr = memberfn; // rewrite pointer
void *result = (foo->*f.memberfn)();

A pointer to member function can't be stored in a pointer to function because it needs more information (for instance in case of multiple inheritance an offset may have to be applied to this before the call). So you can't do without knowledge of implementation details.
If you want to be portable, the easiest is for your library to provide wrapper functions doing the member call.

Unfortunately a member function pointer has more information than a standard function pointer, and when you get the standard function pointer, converting it to a member function pointer would effectively be trying to generate extra data out of thin air.
I don't think there's any portable way to do what you're attempting, although if the union appears to work you could probably get away with that. Again, you would need to know the representation and calling convention for these methods for each compiler you wish to use to build the bode.
If you know the member function's name, why can't you just do foo->dummy() for example? Otherwise either the lookup function needs to provide a full member function pointer or the library would have to provided a C wrapper interface with normal functions to which a this pointer can be passed.

The following two links provide insight and possibly a solution. Note that calling a member function pointer with a this argument usually don't work, since you must take into account virtual methods, multiple and virtual inheritance.
http://www.codeproject.com/KB/cpp/FastDelegate.aspx
http://www.codeproject.com/KB/cpp/ImpossiblyFastCppDelegate.aspx

According to the answer below it is doable in GCC, but not portable:
https://stackoverflow.com/a/5067992/705086

Related

Non virtual pointer in c++?

Is it possible to have a “non virtual pointer” in c++ ( ie a pointer that calls the methods directly without dynamic dispatch). This is because I am trying to do something like this:
template <typename T>
class Ref {
T* value; // I am 100% sure that value points to an actual T object.
/* constructors and stuff */
auto operator -> () {
return value;
}
};
But this will unnecessarily call virtual functions when I know the dynamic type of value to be T...
I know that the user could enforce the usage of non-virtual functions like so:
X->Base::foo();
But that seems like another burden for the user. How can this be done automatically?
when I know the dynamic type of value to be T
You may know/assume this, but at present, there is no mechanism in C++ that can make the language know/assume this for any given pointer/reference to an object. If it is of a polymorphic type, then calling any virtual function (unless the caller explicitly specifies otherwise) will use dynamic dispatch.
Say your class T marks its virtual functions with final, the function calls should be devirtualized on all modern compilers.
See: https://quuxplusone.github.io/blog/2021/02/15/devirtualization/

C++: How to call a member function pointer that is a member of the same class?

I'm trying to implement more flexibility in my numerics by allowing me to choose different forms of a mathematical function and vary their parameters through instantiating them as objects of a certain class. That class includes certain mathematical functions I may choose plus parameters that I can vary. The constructor of the class sets a member function pointer in the class to a member function according to what mathematical function I want. I want to solely use the pointer to call whatever function it points to by directly using the pointer in my routine.
However, that proved daunting as I didn't know that member function pointers require a certain syntax and seem to work somewhat differently from regular function pointers according to what I could gather. I've experimented quite a bit and constructed myself a minimal example shared below.
#include<iostream>
#include<string.h>
#include<cstdlib>
#include<stdio.h>
class Someclass
{
public:
// constructor to set pointer
Someclass(std::string);
// member function pointer to hold functions
void (Someclass::*fptr)();
// auxiliary function to call testfunction via pointer
void call ();
// testfunction
void foo();
};
// testfunction
void Someclass::foo()
{
printf("foo says hi! \n");
}
// call via specific function
void Someclass::call()
{
(this->*fptr)();
}
// constructor
Someclass::Someclass(std::string name)
{
if(name=="foo")
{
this->fptr = &Someclass::foo;
}
}
int main()
{
Someclass someobject("foo");
someobject.foo(); // direct testfunction call: Works OK
someobject.call(); // call via auxiliary function: Works OK
//(someobject.*fptr)(); // direct pointer dereferencing: Gives Error
return(EXIT_SUCCESS);
}
It shows that I can access the pointer by use of another member function that just calls whatever the pointer points to via use of a this pointer. However, I still can't seem to get the function call to work if I try to use the pointer directly in my main function through the line,
(someobject.*fptr)()
This particular expression leads to my compiler complaining about the scope and if I include the class scope, the compiler mentions invalid use of non-static members. Still, I'm confused as to why my implementation here doesn't work and if it does, how the proper syntax in my problem would be and why that has to be so.
Any insights would be really appreciated.
fptr is a member of the object, not a variable local to main. In such respect member function pointers behave exactly the same as all other variable types. You were so close, and just need to qualify the function pointer name with the object name:
(someobject.*(someobject.fptr))();
The reasons for this is .* indicates a pointer to member function and does not directly reference the members of an object like the . and .-> operators. Since fptr is a member of Someclass and not a local variable you need to reference it directly like so
(someobject.*someobject.fptr)();

Pass a non-static method pointer as an argument to another method

Sorry to ask such a question as I'm sure it's been answered before, but I'm struggling to find an answer and it's not for the want of looking... anyway..
class foo
{
void read(void (*func)(obj&))
{
// many things happen to obj...
(*func)(obj); // Calls the function pointer to the handler.
}
};
class bar : public foo
{
void handler(obj&)
{
//
}
};
void main()
{
foo f;
typedef void (foo::*funcptr)(obj&);
funcptr ptr = &foo::handler;
f.read(ptr); ????
}
So basically, all I'm trying to do is pass the non-static member method called handler as a function pointer to the read method, so that when the callback is executed, the handler is called.
I've tried all sorts of ways to make this work and don't want to make static methods (for reasons I won't go into). I think I'm pretty close, but have sort of fallen over right at the end! Any help would be appreciated.
You cannot do that: unlike static functions that can be called on their own, the call of a member function requires knowledge of two things - the function being called, and the object on which to call it. That is why it is not possible to pass a member function to an API expecting a "plain" function pointer.
If you do not have access to the source of the foo class, you can create a static function that calls a member function on an object stored at a well-known location (i.e. in a static variable). If you do, consider changing the API to take a function object, similar to what functions from the standard C++ library do.
Finally, there is a common approach used in C libraries that take function pointers - passing an additional void* pointer, which will be passed back in a call to your function pointer; pthreads library does that. If this is the case, you can create a struct that wraps the invocation target object, and pass a pointer to this struct to be passed back to your static function.
AFAIK I don't think there is any other way. You will have to make the method static.

Why is the "this" prefix required when invoking a member function via a function pointer?

AFAIK, in C++, invoking another member function within a member of function of the same class should not require the "this" prefix as it is implicit. However, in the specific case of using function pointers, the compiler requires it. The following code compiles correctly only if I include the "this" prefix for the call via func pointer -
When function pointers are used can the compiler deduce when it points a member func of the same class?
class FooBar
{
private:
int foo;
public:
FooBar()
{
foo = 100;
}
int GetDiff(int bar)
{
return abs(foo - bar);
}
typedef int(FooBar::*MyFuncPtr)(int);
void FooBar::Bar()
{
MyFuncPtr f = &FooBar::GetDiff;
(this->*f)(10);
GetDiff(10);
}
};
It's required, because member function pointers (which are not the same thing as function pointers) are not bound, and you can use them with different objects.
(this->*f)(10);
(foo.*f)(10);
// etc.
When you invoke an instances member function the this pointer is implicitely put to the function parameters. Thus you need to specify this also when invoking that function via a function pointer.
f isn't a member of the class, but a local variable, you could also specify another instance pointer instead of this, so the compiler can't deduce that. Same for member function pointers as class member variables.
The simple question is that it is a matter of language design and the language was designed this way.
Inside a member function, and to ease the common syntax when the compiler encounters an identifier it performs lookup starting from this class (plus ADL on the arguments), and if the lookup finds an unambiguous non-static member of this type (or of a base type) then the compiler will inject this-> for you (that is, applies operator-> to the this pointer).
In the case of a pointer to member the process is quite different. The pointer (which is not really a pointer, but for the sake of argument) is found by lookup, but it is your responsibility to provide the object on which it will be called and use the appropriate operator (either .* for calling a pointer to member on a reference, or ->* for calling the member on a pointer).
Note that the operators that are called are different, and that the process is different altogether (in one case lookup finds a member, in the other it finds a variable that happens to be pointer-to-member), but the most important part is that calling pointers to members is infrequent enough, and calling them on this is even less frequent that it does not not to warrant an exemption on the syntax for a small use case.
f isn't a member of FooBar. So if you want to call f on an instance of FooBar, you have to tell it which instance.
In your example, f does contain a member of FooBar, but the compiler doesn't know that.
This happens because of the way the C++ runtime handles classes while you are not looking.
Basically it would be inefficient to store the function pointers in the instance, so the compiler builds a class specific table with function pointers that have the same arity as the member functions you defined and that get the this pointer passed at runtime (AFAIK visualc passes the pointer via ecx, I'm not entirely sure what happens on GCC)
So basically when you do
instance->foo(10);
You are telling the runtime to call function foo with the parameter 10 and pass (instance) as the this pointer, wich is why you have to specifically say which object it has to be called on.

Help needed in Use of Function pointer in C++

i have made a sample example, in this i'm trying to pass a function as argument i am getting error, could you please help me
typedef void (*callbackptr)(int,int);
class Myfirst
{
public:
Myfirst();
~Myfirst();
void add(int i,callbackptr ptr)
{
ptr(i,3);
}
};
class Mysec
{
public:
Myfirst first_ptr;
Mysec();
~Mysec();
void TestCallback()
{
callbackptr pass_ptr = NULL;
pass_ptr = &Mysec::Testing;
first_ptr.add(2,&Mysec::Testing);
}
void Testing(int a,int b)
{
int c = a+b;
}
};
The type of the callback function you're passing as parameter is not defined as part of a class. You probably should define Testing as static.
You are geting an error because you are pointing to a member function. Pointers to member functions are different. See here:
http://www.parashift.com/c++-faq-lite/pointers-to-members.html#faq-33.1
A member function needs to know what instance it is working with (the this pointer) so it can't be called like any other function. If you moved the callback function out of the class (or made it static, which is similar to moving it out of the class) you could call it like any other function.
A more modern way of doing this is to use functors, e.g. boost::function and something like boost::bind :
C++ Functors - and their uses
how boost::function and boost::bind work
Those can hide the difference between member and global functions.
You are trying to access a member function pointer here, using a simple function pointer typedef, which will not work. Let me explain.
When you write a normal, non-member function (similar to C), the function's code actually exists in a location indicated by the name of the function - which you would pass to a function pointer parameter.
However, in the case of a member function, all you have is the class definition; you don't have the actual instance of the class allocated in memory yet. In such a function, since the this pointer is not yet defined, any reference to member variables wouldn't make sense, since the compiler doesn't have enough information to resolve their memory locations. In fact, member function pointers are not exact addresses; they encode more information than that (which may not be visible to you). For more, read Pointers to Member Functions.