This question already has answers here:
Function pointer to different functions with different arguments in C
(6 answers)
Closed 9 years ago.
is there any possibility for function pointer for addressing function with different no of arguments of same return type, if not any alternate would be helpful.. thanks in advance
example:
struct method
{
char *name;
void (*ptr)(?); //? : what to define as arguments for this
};
void fun1(char *name)
{
printf("name %s\n\r",name);
}
void fun2(char *name, int a)
{
printf("name %s %d\n\r",name,a);
}
//defined before main()
method def[]=
{
{"fun1",fun1},
{"fun2",fun2}
}
//some where in main()
//call for function pointer
def[1].ptr("try", 2);
typedef void (*myfunc)(char *,int);
struct method
{
char *name;
myfunc ptr;
};
method def[]=
{
//we store fun1 as myfun
//type void(char*,int) and use it this way
{"fun1",(myfunc)fun1},
{"fun2",fun2}
};
This is by theory undefined behavior, but in reality it should work on most platforms
* edit -> this works on all plaforms just like printf(const char*,...) does.
In C, you can make your function pointer declaration read
void (*ptr)();
Which means 'A pointer to a function returning void and expecting an unspecified number of argments.'
With that adjustement, your sample program works as expected to me. However, it may well be that you're venturing into undefined (or at least implementation defined) lands here - I don't know for sure and I'm not a language lawyer (however there are plenty of language lawyers frequenting SO, so I'm sure somebody can whip up the relevant section of the standard or prove that there is none). So maybe you should rather use
/* Here be dragons! */
void (*ptr)();
instead.
Solution #1:
void fun1(char *name, ...);
void fun2(char *name, ...);
Solution #2:
method def[]=
{
{"fun1",printf},
{"fun2",printf}
}
Related
This question already has answers here:
Understanding typedefs for function pointers in C
(8 answers)
Typedef function pointer?
(6 answers)
Closed 9 years ago.
I am reading Linux kernel recently.
I find that in many cases they use the struct "typedef xxx f(xxx)", but I cannot understand how it works. (something like function pointer?)
Here is my test code.
#include<stdio.h>
typedef int Myfunc(int);
typedef int (*point_to_myfunc)(int);
static Myfunc example;
static int example(int a){
printf("example a=%d\n", a);
return 1;
}
static void example2(Myfunc* f){
printf("example2\n");
f(2);
}
static void example3(int (*)(int));
static void example3(int (*point_to_Myfunc)(int)){
printf("example3\n");
point_to_Myfunc(3);
}
int main(){
point_to_myfunc f=&example;
example2(f);
example3(f);
return 0;
}
Can anyone provide a brief explanation for me? Thx~
#include <stdio.h>
typedef int Myfunc(int);
Myfunc is the name of a type; it is a function taking an int argument and returning an int.
typedef int (*point_to_myfunc)(int);
point_to_myfunc is a pointer to a function taking an int argument and returning an int. You could also have: typedef Myfunc *ptr_to_myfunc; if you wished (another name for the same type).
static Myfunc example;
This says 'there exists a function called example of type Myfunc'.
static int example(int a)
{
printf("example a=%d\n", a);
return 1;
}
This is a possible implementation of example. You can't use a typedef name to like Myfunc in the definition of a function of that type.
static void example2(Myfunc *f)
{
printf("example2\n");
f(2);
}
This is a function that takes a pointer to a Myfunc. The line f(2); invokes the function pointed at with the argument 2 and ignores the returned value.
static void example3(int (*)(int));
This declares example3 as a function taking a pointer to a function that takes an int argument and returns an int result. It could have been written as static void example3(point_to_myfunc); or static void example3(ptr_to_myfunc); or static void example3(Myfunc *);.
static void example3(int (*point_to_Myfunc)(int))
{
printf("example3\n");
point_to_Myfunc(3);
}
This is an implementation of example3.
int main(void)
{
point_to_myfunc f = &example;
example2(f);
example3(f);
return 0;
}
This program has a variable f that's a pointer to a function. Interestingly, you could have:
point_to_myfunc f2 = example;
point_to_myfunc f3 = *example;
Etc. And they all mean the same thing.
You could also invoke them using:
(*f2)(101);
(**f3)(103);
The standard notation for the initialization would use neither the & nor the *. If you're an old school C programmer, you may well invoke the function pointer using the (*f2)(101) notation; before the C89 standard, that was the only way to invoke function pointers. Modern style tends to be f2(101); instead.
Vaughn Cato is correct,
In addition,
typedef int (*point_to_myfunc)(int);
defines a function pointer, it means point_to_myfunc is a type,we can use it like this:
point_to_myfunc f=&example;
now f is just like example(), we could f() to call method example
typedef int Myfunc(int);
This means that Myfunc is the type of a function which takes an int parameter and returns an int.
This line:
static Myfunc example;
is the same as saying
static int example(int);
which forward-declares the example function.
One use for this would be to make it clearer that a particular set of functions are used for a particular purpose.
typedef char CharacterConverter(char);
extern CharacterConverter make_upper_case;
extern CharacterConverter make_lower_case;
extern void process_string(char *s,CharacterConverter *f);
// easier to see that make_upper_case and make_lower_case are valid arguments.
typedef is useful when define a type.
For example:
char *a, b; defined a pointer "a", and a char b.
char *a, *b defined two char pointers.
If use typedef, it will be clear:
typedef char* PCHAR;
PCHAR a,b;
Now, both a and b is a char pointer.
typedef int Myfunc(int);
typedef int (*point_to_myfunc)(int);
the two lines defined a pair, a function format and a type of pointer which can point to the function, so it will be clear and more obvious when using them.
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.
This question is similar to what I'm trying to do Calling C++ member function pointer from a struct .
However my structure contains a member function pointer that is defined in a different class then the one the structure is defined and used in. Here is some example code of how my classes, structures and function pointers are laid out.
// Alpha.h:
class Alpha{
public:
void function1(char name[], int number);
void function2(char name[], int number);
void function3(char name[], int number);
typedef void (Alpha::*My_func_ptr)(char name[], int number);
static My_func_ptr functionTable[];
};
// Alpha.cpp:
#include "Alpha.h"
Alpha::My_func_ptr Alpha::functionTable[] = {
&Alpha::function1,
&Alpha::function2,
&Alpha::function3
};
void Alpha::function1(char name[], int number)
{
//some stuff
}
void Alpha::function2(char name[], int number)
{
//some stuff
}
void Alpha::function3(char name[], int number)
{
//some stuff
}
// Beta.h:
#include "Alpha.h"
typdef struct{
char bName[10];
Alpha::My_func_ptr fptr;
}ptr_structure;
class Beta{
public:
void betafunction();
Alpha alphaobject;
ptr_structure str_array[3];
};
// Beta.cpp:
#include "Beta.h"
void betafunction()
{
str_array[0].fptr = alphaobject.functionTable[0];
str_array[1].fptr = alphaobject.functionTable[1];
str_array[2].fptr = alphaobject.functionTable[2];
(str_array[0].fptr)("name", 1); //gives error expression must have
//(pointer-to-) function type
(this->*str_array[0].fptr)("name", 1);
//error pointer-to-member selection class types are incompatible "Beta" and "Alpha"
//sample function pointer call using function table from other class,
//this syntax compiles and runs without error.
(alphaobject.*Alpha::functionTable[0]("name", 1);
}
As you can see I can call the function pointer from an array, but can't seem to figure out how to call a function pointer from inside an array of structures.
When calling a through member function pointer, you need to have an instance of the object associated with that pointer:
(alphaobject.*(str_array[0].fptr))("name", 1)
^^^^^^^^^^^
I would think:
(object.*functionTable[0])(args, ...);
(objptr->*functionTable[0])(args, ....);
IIRC, the combination of object and the .* operator is like a big unary operator. So that has lower precedence to the [0] postfix. However, it also has lower prededence than the function call postfix operator (args, ...)
Analogy:
(*foo)(); /* classic C */
Of course the * operator is not required when calling a regular function. But if you do write it, you need the parens, because *foo() means something else.
You can go to one of two solutions, depending on how readable you want the code. The unreadable version (which might even be wrong, and I won't even try to compile):
void Beta::betafunction() {
Alpha a;
(a.*(strArray[0].fptr))("name",1);
}
But I would actually try to make things a bit simpler:
void Beta::betafunction() {
Alpha a;
Alpha::My_func_ptr mptr = strArray[0].fptr;
(a.*mptr)("name",1);
}
I believe the second to be much more readable, and the compiler can optimize away mptr pretty easily, so there is no point in trying to play guru with the syntax.
Hi I am trying to learn some function pointers in C/C++ and I was trying to write the following C++ code with gcc on Ubuntu.
This code should execute the multiply or or the add function depending on the
preprocessor flag -DADD or -DMULTIPLY provided during compilation
#include <iostream>
#include <iomanip>
//Adds two numbers
int add(int a, int b)
{
return a+b;
}
//Multiplies two numbers
int multiply(int a, int b)
{
return a*b;
}
//Function to set the correct function to be executed.
//All functions here should have the same signature.
void functionsetter( void (*ptr2fun)(int,int) )
{
#ifdef ADD
ptr2fun = add;
#endif
#ifdef MULTIPLY
ptr2fun = multiply
#endif
}
int main(int argc, char *argv[])
{
int a = 5;
int b = 6;
void (*foo)(int,int);
functionsetter(foo);
return 0;
}
I cannot figure out how to pass the function pointer foo to the function-setter function by reference. Can someone help me out on this.I am sure the declaration of
functionsetter is wrong in the code, Please let me know how to fix it.
I am trying to compile this with g++ -O2 -g -Wall -DADD main.cpp -o main
Note: I want to use such preprocessor flags and function pointers in some other-code elsewhere.
Please let me know if such a thing is a good idea / practice.
Without using a typedef, the syntax for a reference to a function pointer is:
void functionsetter(void (*&ptr2fun)(int, int)) { ... }
But it is generally simpler to create a typedef for the pointer type:
typedef void (*FunctionPointer)(int, int);
void functionsetter(FunctionPointer& ptr2fun) { ... }
Or for the function type:
typedef void Function(int, int);
void functionsetter(Function*& ptr2fun) { ... }
Use a typedef:
typedef void (*MyFunctionPointer)(int,int);
void functionsetter(MyFunctionPointer& fp);
I want to use such preprocessor flags and function pointers in some other-code elsewhere. Please let me know if such a thing is a good idea / practice.
No, not really. It isn't clear from your example what you are trying to accomplish, but your implementation is rather unusual. Consider using virtual member functions or std::function to switch function implementations at runtime, or (possibly) templates to switch them at compile-time. There's nothing wrong with using conditional compilation for static selection like this, but mixing that with function pointers is a bit odd.
Without a good understanding of the problem you are trying to solve, it's difficult to give good advice as to how best to solve it.
You'd change your signature to:
void functionsetter( void (*&ptr2fun)(int,int) )
Note that the ptr2fun function pointer has the wrong signature, your add and multiply functions return an int, and so should ptr2fun
This becomes a lot easier if you use a typedef:
typedef int (*ptr2fun)(int,int);
void functionsetter(ptr2fun& func) { ...
Though, personally I'd just return the function pointer.
ptr2fun functionsetter()
{
#ifdef ADD
return add;
#endif
#ifdef MULTIPLY
return multiply
#endif
}
First, you're not passing a function pointer reference to the method, you're just passing a function pointer. You need to change the method signature to
void functionsetter( void (*&ptr2fun)(int,int) )
Also, your method signature is void(*)(int,int) in some places and int(*)(int,int) in some, they should probably be the latter everywhere since your add and multiply methods return int.
That said, since you're using C++, manipulating pointers in this manner isn't something I'd recommend, C++ has inheritance/virtual methods that can usually replace most function pointer use and makes the code much more readable and extensible.
We can declare functions inside functions (I wanted a local variable, but it parses as a function declaration):
struct bvalue;
struct bdict {
bdict(bvalue);
}
struct bvalue {
explict operator bdict() const;
}
struct metainfo {
metainfo(bdict);
}
void foo(bvalue v) {
metainfo mi(bdict(v)); // parses as function declaration
metainfo mi = bdict(v); // workaround
// (this workaround doesn't work in the presence of explicit ctors)
}
Are the sole reasons "because it makes the parser simpler" and "because the standard says so", or is there an obscure use for this?
This is really a C question, because this behaviour was inherited directly from C (although it gets much more press in C++ because of the most vexing parse).
I suspect the answer (in the context of C, at least) is that this allows you to scope the existence of your function declarations to precisely where they're needed. Maybe that was useful in the early days of C. I doubt anyone does that any more, but for the sake of backward compatibility it can't be removed from the language.
It's useful if you need to use an external function whose name would conflict with an internal (static) function or variable in the current translation unit (source file). For instance (silly but it gets the point across):
static int read(int x)
{
return bar(x);
}
static int foo()
{
ssize_t read(int, void *, size_t);
read(0, buf, 1);
}
A function declaration inside another function hides other overloaded functions. e.g. Compiler error on Line 7
#include <iostream>
void f(int);
int main() {
void f(char *);
f(10); // Line 7
f("Hello world");
return 0;
}
void f(int a) {
std::cout << a;
}
void f(char *str) {
std::cout << str;
}
Are the sole reasons "because it makes
the parser simpler" and "because the
standard says so"
Yea, basically.
Everything that can be a function declaration, is a function declaration.
Unfortunately it's one of those "just is" cases.