Reputation: 11045
I don't know if what I am trying to do is possible but it would be grate to be. It will really prove that C++ is a strong language.
So, I have a DLL and an EXE that uses a function exported by the DLL. That function takes an argument which is, or must be a pointer to another function, and executes it. Something like this:
extern void RunFunction(void (*FunctionPonter)()) {
(*FunctionPonter)();
}
and I call it like this:
RunFunction(&FunctionToExecute);
The function sent as an argument will not have arguments, just a void function.
So, all this works, as it is presented here. Now, I would like to go further and define (*void)()
as, for example, Action
.
typedef (*void)() Action;
Action FunctionToExecute() {
// My code. This function won't return results - void
}
and I would like to send the pointer to the function in my DLL like this:
// This is how it would be declared now in the DLL
extern void RunFunction(void (ACTION) {
(*FunctionPonter)();
}
// and this is how I would like to use it
RunFunction(FunctionToExecute);
I am using VC2010 and I don't know how could I do that, if it is possible. Thanks for your ideas, explanations and help!
Upvotes: 0
Views: 852
Reputation: 320541
Firstly, the proper syntax for function type typedef
is
typedef void (*Action)();
Secondly, typedef-name for function type can be used to declare functions of that type, but they cannot be used to define such functions. I.e. if FunctionToExecute
is the function you wat to execute through the pointer, then it has to be defined as
void FunctionToExecute() {
/* whatever */
}
The calling function would be defined as
void RunFunction(ACTION p) {
p();
}
And the call to it would look as follows
RunFunction(FunctionToExecute);
That's it. Unary *
and &
operators are optional with function pointers.
Upvotes: 2
Reputation: 272537
Ok, if I understand your question correctly, you're looking for a way to only allow certain functions to be passed as arguments to your DLL function.
Using a typedef won't work, as that just creates an alias; Action
and void (*)()
are indistinguishable to the compiler in your code. Instead, you'll have to create a brand new type. In C++, you should strongly consider using a functor:
// Abstract functor
struct Action {
virtual void operator() () const = 0;
};
// The DLL function
void RunFunction(const Action &action) {
action();
}
// Define your function as a derived functor
struct FunctionToExecute : Action {
void operator() () const { std::cout << "Hello\n"; }
};
// Run a function
RunFunction(FunctionToExecute());
Demo: http://ideone.com/5pl23.
Upvotes: 2