I'm getting a compile error (MS VS 2008) that I just don't understand. After messing with it for many hours, it's all blurry and I feel like there's something very obvious (and very stupid) that I'm missing. Here's the essential code:
typedef int (C::*PFN)(int);
struct MAP_ENTRY
{
int id;
PFN pfn;
};
class C
{
...
int Dispatch(int, int);
MAP_ENTRY *pMap;
...
};
int C::Dispatch(int id, int val)
{
for (MAP_ENTRY *p = pMap; p->id != 0; ++p)
{
if (p->id == id)
return p->pfn(val); // <--- error here
}
return 0;
}
The compiler claims at the arrow that the "term does not evaluate to a function taking 1 argument". Why not? PFN is prototyped as a function taking one argument, and MAP_ENTRY.pfn is a PFN. What am I missing here?
p->pfn is a pointer of pointer-to-member-function type. In order to call a function through such a pointer you need to use either operator ->* or operator .* and supply an object of type C as the left operand. You didn't.
I don't know which object of type C is supposed to be used here - only you know that - but in your example it could be *this. In that case the call might look as follows
(this->*p->pfn)(val)
In order to make it look a bit less convoluted, you can introduce an intermediate variable
PFN pfn = p->pfn;
(this->*pfn)(val);
Try
return (this->*p->pfn)(val);
Just to chime in with my own experience, I've come across an error in g++ caused by this statement:
(this -> *stateHandler)() ;
Where stateHandler is a pointer to a void member function of the class referenced by *this. The problem was caused by the spaces between the arrow operator. The following snippet compiles fine:
(this->*stateHandler)() ;
I'm using g++ (GCC) 4.4.2 20090825 (prerelease). FWIW.
p->pfn is a function pointer. You need to use * to make it function. Change to
(*(p->pfn))(val)
Related
I'm trying to make a table of function pointers within a class. I haven't been able to find any examples of this online, most involve using member function pointers outside of their class.
for example:
class Test
{
typedef void (Test::*FunctionType)();
FunctionType table[0x100];
void TestFunc()
{
}
void FillTable()
{
for(int i = 0; i < 0x100; i++)
table[i] = &Test::TestFunc;
}
void Execute(int which)
{
table[which]();
}
}test;
Gives me the error "term does not evaluate to a function taking 0 arguments".
In this line in the Execute function:
table[which]();
You can't call it like that because it's not a normal function. You have to provide it with an object on which to operate, because it's a pointer to a member function, not a pointer to a function (there's a difference):
(this->*table[which])();
That will make the invoking object whichever object is pointed to by the this pointer (the one that's executing Execute).
Also, when posting errors, make sure to include the line on which the error occurs.
Seth has the right answer. Next time, look up the compiler error number on MSDN and you'll see the same: Compiler Error C2064.
You need a context in which to call your function. In your case, the context is this:
void Execute(int which)
{
(this->*table[which])();
}
I'm trying to get function addresses which are hidden behind structures. Unfortunately, the void* basic C++ conversion doesn't work, so I used C++ template instead.
1. Basic void* C++ conversion doesn't work with functions inside structures, why?
void * lpfunction;
lpfunction = scanf; //OK
lpfunction = MessageBoxA; //OK
I made a simple structure :
struct FOO{
void PRINT(void){printf("bla bla bla");}
void SETA(int){} //nothing you can see
void SETB(int){} //nothing you can see
int GETA(void){} //nothing you can see
int GETB(void){} //nothing you can see
};
///////////////////////////////////////////
void *lpFunction = FOO::PRINT;
And the compiling error :
error C2440: 'initializing' :
cannot convert from 'void (__thiscall FOO::*)(void)' to 'void *'
2. Is getting function member addresses impossible?
Then, I made a template function which is able to convert a function member to address. Then I will call it by assembly. It should be something like this:
template <class F,void (F::*Function)()>
void * GetFunctionAddress() {
union ADDRESS
{
void (F::*func)();
void * lpdata;
}address_data;
address_data.func = Function;
return address_data.lpdata; //Address found!!!
}
And here is the code :
int main()
{
void * address = GetFunctionAddress<FOO,&FOO::PRINT>();
FOO number;
number.PRINT(); //Template call
void * lpdata = &number;
__asm mov ecx, lpdata //Attach "number" structure address
__asm call address //Call FOO::PRINT with assembly using __thiscall
printf("Done.\n");
system("pause");
return 0;
}
But, I see it is extremely specific. It looks like LOCK - KEY, and I have to make a new template for every set of argument types.
Original (OK) :
void PRINT(); //void FOO::PRINT();
Modify a bit :
void PRINT(int); //void FOO::PRINT(int);
Immediately with old template code the compiler shows :
//void (F::*func)();
//address_data.func = Function;
error C2440: '=' : cannot convert from
'void (__thiscall FOO::*)(int)' to 'void (__thiscall FOO::*)(void)'
Why? They are only addresses.
69: address_data.func = Function;
00420328 mov dword ptr [ebp-4],offset #ILT+2940(FOO::PRINT) (00401b81)
...
EDIT3 : I know the better solution :
void(NUMBER::*address_PRINT)(void) = FOO::PRINT;
int(NUMBER::*address_GETA)(void) = FOO::GETA;
int(NUMBER::*address_GETB)(void) = FOO::GETB;
void(NUMBER::*address_SETA)(int) = FOO::SETA;
void(NUMBER::*address_SETA)(int) = FOO::SETB;
It's much better than template. And by the way I want to achieve the goal :
<special_definition> lpfunction;
lpfunction = FOO::PRINT; //OK
lpfunction = FOO::GETA; //OK
lpfunction = FOO::GETB; //OK
lpfunction = FOO::SETA; //OK
lpfunction = FOO::SETB; //OK
Is this possible?
Pointers to member functions are nothing like pointers to global functions or static member functions. There are many reasons for this, but I'm not sure how much you know about how C++ works, and so I'm not sure what reasons will make sense.
I do know that what you are trying in assembly simply won't work in the general case. It seems like you have a fundamental misunderstanding about the purpose of member functions and function pointers.
The thing is, you are doing some things that you would generally not do in C++. You don't generally build up tables of function pointers in C++ because the things you would use that sort of thing for are what virtual functions are for.
If you are determined to use this approach, I would suggest you not use C++ at all, and only use C.
To prove these pointer types are completely incompatible, here is a program for you:
#include <cstdio>
struct Foo {
int a;
int b;
int addThem() { return a + b; }
};
struct Bar {
int c;
int d;
int addThemAll() { return c + d; }
};
struct Qux : public Foo, public Bar {
int e;
int addAllTheThings() { return Foo::addThem() + Bar::addThemAll() + e; }
};
int addThemGlobal(Foo *foo)
{
return foo->a + foo->b;
}
int main()
{
int (Qux::*func)();
func = &Bar::addThemAll;
printf("sizeof(Foo::addThem) == %u\n", sizeof(&Foo::addThem));
printf("sizeof(Bar::addThemAll) == %u\n", sizeof(&Bar::addThemAll));
printf("sizeof(Qux::addAllTheThings) == %u\n", sizeof(&Qux::addAllTheThings));
printf("sizeof(func) == %u\n", sizeof(func));
printf("sizeof(addThemGlobal) == %u\n", sizeof(&addThemGlobal));
printf("sizeof(void *) == %u\n", sizeof(void *));
return 0;
}
On my system this program yields these results:
$ /tmp/a.out
sizeof(Foo::addThem) == 16
sizeof(Bar::addThemAll) == 16
sizeof(Qux::addAllTheThings) == 16
sizeof(func) == 16
sizeof(addThemGlobal) == 8
sizeof(void *) == 8
Notice how the member function pointer is 16 bytes long. It won't fit into a void *. It isn't a pointer in the normal sense. Your code and union work purely by accident.
The reason for this is that a member function pointer often needs extra data stored in it related to fixing up the object pointer it's passed in order to be correct for the function that's called. In my example, when called Bar::addThemAll on a Qux object (which is perfectly valid because of inheritance) the pointer to the Qux object needs to be adjusted to point at the Bar sub-object before the function is called. So Qux::*s to member functions must have this adjustment encoded in them. After all, saying func = &Qux::addAllTheThings is perfectly valid, and if that function were called no pointer adjustment would be necessary. So the pointer adjustment is a part of the function pointer's value.
And that's just an example. Compilers are permitted to implement member function pointers in any way they see fit (within certain constraints). Many compilers (like the GNU C++ compiler on a 64-bit platform like I was using) will implement them in a way that do not permit any member function pointer to be treated as at all equivalent to normal function pointers.
There are ways to deal with this. The swiss-army knife of dealing with member function pointers is the ::std::function template in C++11 or C++ TR1.
An example:
#include <functional>
// .... inside main
::std::function<int(Qux *)> funcob = func;
funcob can point at absolutely anything that can be called like a function and needs a Qux *. Member functions, global functions, static member functions, functors... funcob can point at it.
That example only works on a C++11 compiler though. But if your compiler is reasonably recent, but still not a C++11 compiler, this may work instead:
#include <tr1/functional>
// .... inside main
::std::tr1::function<int(Qux *)> funcob = func;
If worse comes to worse, you can use the Boost libraries, which is where this whole concept came from.
But I would rethink your design. I suspect that you will get a lot more milage out of having a well thought out inheritance hierarchy and using virtual functions than you will out of whatever it is you're doing now. With an interpreter I would have a top level abstract 'expression' class that is an abstract class for anything that can be evaluated. I would give it a virtual evaluate method. Then you can derive classes for different syntax elements like an addition expression a variable or a constant. Each of them will overload the evaluate method for their specific case. Then you can build up expression trees.
Not knowing details though, that's just a vague suggestion about your design.
Here is a clean solution. By means of a template wrap your member function into a static member function. Then you can convert it to whatever pointer you want:
template<class F, void (F::*funct)()>
struct Helper: public T {
static void static_f(F *obj) {
((*obj).*funct)();
};
};
struct T {
void f() {
}
};
int main() {
void (*ptr)(T*);
ptr = &(Helper<T,&T::f>::static_f);
}
It seems that you need to convert a pointer to a member function to a void *. I presume you want to give that pointer as a "user data" to some library function and then you will get back your pointer and want to use it on some given object.
If this is the case a reinterpret_cast<void *>(...) could be the right thing... I assume that the library receiving the pointer is not using it.
For the following code snippets why would I use one assignment vs another? thx
void addOne(int &x)
{
x +=1;
}
void (*inc)(int &x) = addOne; // what is the purpose of doing "addOne"
void (*inc)(int &x) = &addOne; // vs &addOne ??
int a = 10;
inc(a);
The purpose of one over the other is C compatibility. C said that functions will decay to pointers-to-functions automatically. To be compatible, C++ had to do the same.
Note that when C++ introduced a new function pointer type (member function pointers), they do not decay automatically. So if the C++ committee had their way, odds are good you'd need that & there.
Brevity, style. It's the same with using * when calling them.
Also note array vs &array[0].
From the book C++ Programming Languauge, it is cleary indicated that & and * operators are optional for pointers to functions:
There are only two things one can do to a function: call it and take
its address. The pointer obtained by taking the address of a function
can then be used to call the function. For example:
void error (string s) { /* ... */ }
void (*efct )(string ); // pointer to function
void f ()
{
efct = &error ; // efct points to error
efct ("error "); // call error through efct
}
The compiler will discover that efct is a pointer and call the
function pointed to. That is, dereferencing of a pointer to function
using * is optional. Similarly, using & to get the address of a
function is optional:
void (*f1 )(string ) = &error ; // ok
void (*f2 )(string ) = error ; // also ok; same meaning as &error
void g ()
{
f1 ("Vasa"); // ok
(*f1 )("Mary Rose"); // also ok
}
As others pointed out, pointer to member function is new/different in C++. The & is not optional to point a member and it is explained as (in C++ Programming Languauge Book):
A pointer to member can be obtained by applying the address-of
operator & to a fully qualified class member name, for example,
&Std_interface::suspend.
A function is already a pointer; therefore, you do not need the address operator.
I think I may be suffering from the dreaded "accidental programmer" disease, at least when it comes to typedefs and function pointers. So I've been experimenting with all kinds of combinations involving these to analyse the results based on all the output I get.
But as I kept on trying different combinations, instead of analyzing the results I'm now just lost in process.
I'm hoping you guys will help me figure out this mess.
First code example
typedef void (print)(void);
void do_something (void) { printf("Hello World\n"); }
print *pr;
pr = &do_something;
pr(); // Hello World
Second code example
typedef void (print)(void);
void do_something (void) { printf("Hello World\n"); }
print *pr;
pr = do_something;
pr(); // Hello World
How do both the above code examples work, it's as if '&' has no effect on function name
third code example
typedef void (print)(void);
void do_something (void) { printf("Hello World\n"); }
print pr;
pr = do_something; // compile error
pr = &do_something; // compile error
pr();
I was hoping one of the above assignments to work here but damn! I really don't understand function pointers (and maybe typedef too).
The address of a function name and the plain function name both mean the same thing, so & has no effect on a function name.
Similarly, when using function pointers, multiple dereferencing isn't a problem:
#include <stdio.h>
typedef void print(void);
static void dosomething(void) { printf("Hello World\n"); }
int main(void)
{
print *f1 = dosomething;
print *f2 = &dosomething;
f2();
(f1)();
(*f1)();
(**f2)();
(***f1)();
(****f2)();
(*****f1)();
}
That compiles cleanly under:
gcc -O3 -g -Wall -Wextra -Werror -Wmissing-prototypes -Wstrict-prototypes \
-Wold-style-definition -std=c99 xx.c -o xx
I would not claim that multiple stars is good style; it isn't. It is 'odd, and (yes, you may say it) perverse'. One is sufficient (and the one star is mainly for people like me who learned to program in C before the standard said "it is OK to call a function via a pointer without using the (*pointer_to_function)(arg1, arg2) notation; you can just write pointer_to_function(arg1, arg2) if you like"). Yes, it is weird. No, no other type (or class of types) exhibits the same behaviour, thank goodness.
The thing about function pointers is that they're function pointers! :-) This is how you get your third sample to work:
#include <stdio.h>
typedef void (*print)(void);
// ^
void do_something (void) { printf("Hello World\n"); }
int main (void) {
print pr;
pr = do_something; // &do_something would also work.
pr();
return 0;
}
In terms of whether you use funcName or &funcName, it doesn't matter (in C at least). Section 6.3.2.1 Lvalues, arrays and function designators states:
A function designator is an expression that has function type. Except when it is the operand of the sizeof operator or the unary & operator, a function designator with type "function returning type" is converted to an expression that has type "pointer to function returning type".
It turns out that, in C/C++, both funcname and &funcname will yield the address of funcname and can be assigned to a function pointer variable. This is actually just an oddity of how the syntax was designed for the language(s).
Like C, C++ has pointer to functions: void (*)() for example is a pointer to a function that takes no argument and returns no value. However, C++ has also introduced references to functions void (&)() and there are implicit conversions between the two (though I don't remember the rules exactly).
Therefore:
funcname is a reference to function
&funcname is a pointer to function
Note that taking the address (or a reference to) a function that is overloaded requires a static_cast to the exact type (to resolve the overload).
I would like to pass a pointer by reference to a function, such that i can actually change the address the passed pointer is pointing to and i'd like to assign this argument a default value.
something like this:
in the declaration
void myFunc(SomeType* &var=NULL);
and the definition:
void MyClass::myFunc(SomeType* &var){
if(var!=NULL)
(*var)=(*someOtherPointer);
if(someCondition)
var=NULL;
}
such that a callee can decide whether he wants to call the function with one argument or without argument. And sucht that if he decides to pass an argument, and someCondition holds, the passed pointer will point to NULL afterwards
however - if i try to do it like this i get a:
Error C2440: 'default argument': 'int' cannot be conveted to 'SomeType *&'
Thanks for the help!
NULL is not an lvalue - it cannot be passed by reference. It would be like passing 4 to a function that expects an int&.
The 'int' part is because NULL is a macro - defined 0.
Your best bet would be using a pointer to pass the pointer by reference, i.e. a double pointer. Then, if the parameter is NULL, nothing was passed. If not, it's the address of the pointer that should be modified [to point to NULL if someCondition holds].
The error message says it all: you are passing an integer instead of a reference-to-a-pointer-to-SomeType. To do what you want, you can use a pointer-to-a-pointer-to-SomeType:
void myFunc(SomeType** var=NULL);
void MyClass::myFunc(SomeType** var){
if(var!=NULL && *var!=NULL)
(**var)=(*someOtherPointer);
if(var!=NULL && someCondition)
*var=NULL;
}
You can also consider using boost::optional (not the simplest code you can use, but the option is there):
void f( boost::optional<int&> r = boost::optional<int&>() )
{
if ( r ) *r = 5;
}
int main()
{
int x = 0;
f( x ); std::cout << x << std::endl; // 5, it did change the value
f(); // compiler will default to an empty optional<int&> object
}
Ok, I can see why you'd do this from the perspective of exercising the C++ brain, but would you really do that in production code? It looks like an incredibly misty technique with side effects, when looking at the code as a colleague 1 year later. Did you think of using two separate functions with clear names, one returning a pointer and one doing any other needed work?
Why not just overload the function?
void myFunc() {
//whatever logic should happen if a null pointer is passed in
}
void myFunc(SomeType* &var) {
if(var!=NULL) {
(*var)=(*someOtherPointer);
}
if(someCondition) {
var=NULL;
}
}