more than a general case, I have a very specific example in mind : in GSL (GNU Scientific Library), the main function type used (in order to perform integration, root finding,...) is gsl_function , which have an attribute function whose type is double(*)(double, void *)
Say I want to create a gsl_function from double a_squared(double a) {return a*a};. a__squared 's type is double(*)(double) I would like to create a convert function taking in argument (double(*)(double) f) and returning an object of type double(*)(double, void *) which would satisfy convert(f)(double a, NULL) == f(a)
But after some research, it seems like I can't define another function in my convert function. How to proceed ?
The need to pass a raw function pointer to the GSL API limits your options considerably - you can't use anything based on std::function because there's no way to obtain a function pointer from a std::function (and this rules out lambdas using captures, which would have offered a neat solution).
Given these constraints, here's a possible solution making use of a static wrapper class. You could just as well have put the contents of this class in a namespace, but using the class at least gives some semblance of encapsulation.
typedef double gsl_function_type(double, void*); // typedef to make things a bit more readable...
// static class to wrap single-parameter function in GSL-compatible interface
// this really just serves as a namespace - there are no non-static members,
// but using a class lets us keep the details private
class Convert
{
Convert() = delete; // don't allow construction of this class
// pointer to the function to be invoked
static double (*m_target)(double);
// this is the function we'll actually pass to GSL - it has the required signature
static double target(double x, void*) {
return m_target(x); // invoke the currently wrapped function
}
public:
// here's your "convert" function
static gsl_function_type* convert(double (*fn)(double)) {
m_target = fn;
return ⌖
}
};
There's a live example here: http://coliru.stacked-crooked.com/a/8accb5db47a0c51d
You're trapped by gsl's (poor) design choice of using C (instead of C++) to provide a C-style function pointer. Thus, you cannot use (C++ style) function-objects (functor), but must provide the pointer to a real function and one cannot generate a function in the same way one can genarate functors.
(Not recommended) You can use a global variable to store the actual function (a_squared) and then define a particular gsl_function that actually calls that global variable:
// from some gsl header:
extern "C" {
typedef double gsl_function(double, void*);
// calls func(arg,data_passed_to_func)
double gsl_api_function(gsl_function*func, void*data_passed_to_func);
}
// in your source code
double(*target_func)(double); // global variable can be hidden in some namespace
extern "C" {
double funtion_calling_target(double, void*)
}
double funtion_calling_target(double arg, void*)
{
return target_func(arg);
}
bool test(double x, double(*func)(double))
{
target_func = func;
return x < gsl_api_function(function_calling_target,0);
}
(hiding target_func as static member of some class as in atkins's answer still requires a global variable). This works, but is poor, since 1) this mechanism requires a global variable and 2) only allows one target function to be used a any time (which may be hard to ensure).
(Recommended) However, you can define a special function that takes another function pointer as argument and passes it as data element. This was in fact the idea behind the design of gsl_function: the void* can point to any auxiliary data that may be required by the function. Such data can be another function.
// your header
extern "C" {
double function_of_double(double, void*);
}
inline double function_of_double(double arg, void*func)
{
typedef double(*func_of_double)(double);
return reinterpret_cast<func_of_double>(func)(arg);
}
// your application
bool test(double x, double(*func)(double))
{
return x < gsl_api_function(function_of_double, (void*)(func));
}
This does not require a global variable and works with as many different simultaneous functions as you want. Of course, here you are messing around with void*, the very thing that every sensible C++ programmer abhors, but then you're using a horrible C library which is based on void* manipulations.
Thought I would add my lambda-based attempts at this.
It works fine in principle:
// function we want to pass to GSL
double a_squared(double a) { return a*a; }
typedef double gsl_function_type(double, void*); // convenient typedef
// lambda wrapping a_squared in the required interface: we can pass f directly to GSL
gsl_function_type* f = [](double x, void*) { return a_squared(x); };
But we'd really like to write a method to apply this to any given function. Something like this:
gsl_function_type* convert(double (*fn)(double))
{
// The lambda has to capture the function pointer, fn.
return [fn](double x, void*) { return fn(x); };
}
However, the lambda now has to capture the pointer fn, because fn has automatic storage duration (in contrast to the static function a_squared in the first example). This doesn't compile because a lambda which uses a capture cannot be converted to a simple function pointer, as required by the return value of our function. In order to be able to return this lambda we'd have to use a std::function, but there's no way to get a raw function pointer from that, so it's no use here.
So the only way I've managed to get this to work is by using a preprocessor macro:
#define convert(f) [](double x, void*) { return f(x); }
This then lets me write something like this:
#include <iostream>
using namespace std;
typedef double gsl_function_type(double, void*); // convenient typedef
// example GSL function call
double some_gsl_function(gsl_function_type* function)
{
return function(5.0, nullptr);
}
// function we want to pass to GSL
double a_squared(double a) { return a*a; }
// macro to define an inline lambda wrapping f(double) in GSL signature
#define convert(f) [](double x, void*) { return f(x); }
int main()
{
cout << some_gsl_function(convert(a_squared)) << endl;
}
Personally, as much as I dislike using macros, I would prefer this over my other suggestion. In particular, it solves the problems #Walter pointed out with that idea.
Previous answers - including the accepted one - seem correct, but they are not general enough in case you need to convert other types of function to gsl_function (including member functions for example). So, let me add a more powerful alternative.
If you use the wrapper described here, then you can convert any C++ lambdas to gsl_functions in two simple lines
// Example
gsl_function_pp Fp([&](double x){return a_squared(x);});
gsl_function *F = static_cast<gsl_function*>(&Fp);
This solves any related conversion problems. You can also use std::bind and any std::functions.
Related
Let's assume some third-party developer writes a function
int GetErrorCode(const object * p);
This function returns only certain int values, thus I am tempted to write my own ErrorCode enum class, that contains all the possible return values. Then write a bit updated function:
enum class ErrorCode : int {};
ErrorCode GetErrorCode2(const object * p){
return (ErrorCode)GetErrorCode(p);
}
The problem is I want my function to be named GetErrorCode and not that less-intuitive GetErrorCode2.
How can I possibly achieve that? Maybe there is a way to swap function names or something?
Use namespaces:
namespace MyLibrary {
ErrorCode GetErrorCode(const object *p) {
int origResult = ::ErrorCode(p);
// use :: to explicitly call outer function to avoid recursion
...
}
}
Then you can call the function as:
MyLibrary::GetErrorCode(obj);
Put your function in a namespace that you normally use. You might have a using namespace foo; - er better yet, using foo::GetErrorCode; - for it where you use it, preferably in a function's body.
I'm trying to code a Gameboy emulator and i would like to use a vector of function pointers to call the right function instead of doing a long switch statement.
For example if the program counter point to 0x00 (in memory), the first element of the vector is NOP so void NOP() is called;
but i can't figure how to call the functions.
Z80.h
#include <vector>
using namespace std;
class Z80;
typedef void (Z80::*function_t)();
class Z80
{
public:
vector<function_t> fmap;
...
...
};
Z80.cpp
Z80::Z80()
{
fmap = { &Z80::NOP, &Z80::LDBCnn, &Z80::LDBCmA};
}
void Z80::emulateCycle() {
opcode = memory.readByte(r.pc);
fmap[opcode](); <---ERROR
r.pc++;
}
void Z80::NOP() {
}
this is the error:
IntelliSense: expression preceding parentheses of apparent call must have (pointer-to-) function type
This expression:
fmap[opcode]
gives you a pointer to a member function. You can't just call that - it needs the class instance too. But you're actually calling it from a class method itself - so this is the instance you're looking for:
(this->*fmap[opcode])();
Note that if you want to avoid that bit of syntax and you're using C++11, you can change your fmap to instead be a vector of std::function<void()> and initialize it thusly:
fmap = { std::bind(&Z80::NOP, this), // or [this](){ this->NOP(); }
std::bind(&Z80::LDBCnn, this), // etc.
std::bind(&Z80::LDBCmA, this)};
That will let you actually do:
fmap[opcode]();
I'm not entirely sure that using function pointer in this case is particularly much better than for example a big switch statement.
However, the reason you can't call your member function is that you are not passing your object to the function.
You need this;
(this->*fmap[opcode])();
Another option is to use static/free function pointers, like this:
void (*function_t)(Z80& self);
and call it with:
fmap[opcode](this).
[Or use std::function and std::bind, which covers over the rather (intentionally, apparently) ugly syntax]
I am trying to store a vector(or stack) of functions. The idea is that I have a series of functions that add & remove widgets to the main window. I use a timer alarm & whenever the alarm is called I call the function at the top of the stack of functions.
So my functions will always be of type void. My problem/misunderstanding is how to delcare a stl::stack of void functions & how do I execute that function?
class InstructionScreen
{
std::stack <void*> instructionSteps; // is this how I declare a stack of functions
void runTimerEvent()
{
if ( !instructionSteps.empty() )
{
// call the function at the top of the stack
// how do I call the function?
(*instructionSteps.top()); // is that how?
instructionSteps.pop();
}
}
void step1()
{
// here I create some widgets & add them to the main window
}
void step2()
{
// delete widgets from window
// create some different widgets & add them to the main window
}
void buildStack()
{
instructionSteps.push( (&step1()) ); // is this correct?
instructionSteps.push( (&step2()) );
}
};
A void* pointer is not a legal function pointer. It should be void (*)(), which can be made nicer with a typedef void (*stack_function)().
std::stack<stack_function> instructionSteps;
To push something into it, you don't call the function (like you do with step1()) and you certainly don't take the address of the return (which is void anyways) like you do with &step1(), you just use the function name alone:
instructionSteps.push(step1); // the & can be omitted for free functions
instructionSteps.push(&step2); // equivalent to the above, only a different function
To call stuff from the top of the stack, you actually need to do a call:
(*instructionSteps.top())();
// you missed that -- ^^
The dereference can be omitted too for reasons that would take too long to explain here, search SO. :)
instructionSteps.top()();
The syntax for a static function pointer is like so:
void (*FuncPtr)();
For a member pointer you have to use this syntax:
void (class::*FuncPtr)();
If your functions does not require the functions to be member functions it is a lot cleaner. Once you figured out what kind of functions you need it's easiest to typedef these functions like so:
typedef void(*FuncPtrType)();
typedef void(Class::*MemberFuncPtrType)();
Now you can simply declare a stack with function pointers like so:
std::stack <FuncPtrType> funcPtrStack;
std::stack <MemberFuncPtrType> memberFuncPtrStack;
To get a pointer to a function you simply use the "&" operator like you would to get an address to any other data type in C++:
FuncPtrType funcPtr = &staticFunc; // Somewhere "void staticFunc()" is defined
MemberFuncPtrType memberFuncPtr = &Class::MemberFunc; // Somewhere void "Class::MemberFunc()" is defined
To actually call the function pointers, you would use the "*" operator to get the data back from the pointer (just like any other data type in C++). The only tricky thing is for member functions they need a pointer to the class which makes it very awkward to use. That's why I recommended using static functions to begin with. In any case, here is the syntax:
(*funcPtr)(); // I just called a function with a pointer!
(this->*memberFuncPtr)(); // I just wrote some ugly code to call a member function
Having shown all that, the following code should now make sense:
std::stack <MemberFuncPtrType> memberFuncPtrStack; // Declaring the stack
memberFuncPtrStack.push( &Class::MemberFunc ); // Pushing a function
(ClassPtr->*memberFuncPtrStack.top())(); // Calling the function with ClassPtr
Declare a typedef and make a vector/stack of it:
typedef void (*funcptr)();
std::stack<funcptr> instructionSteps;
Usage:
instructionSteps.push(&step1);
instructionSteps.push(&step2);
See demo here.
Execution:
instructionSteps.top()();
Tip: Use Boost.Function, it's a lot easier. It will not only store functions with precisely the right type, but also anything else that can be called in the same way.
std::stack<boost::function<void()> instructionSteps;
int foo() { return 42; }
instructionSteps.push(foo); // Close enough - return value will be discarded.
typedef void (*fptr)();
class InstructionScreen
{
std::stack <fptr> instructionSteps;
I would typedef the function pointer to make your life easier:
typedef void(*voidFunctionPointer)(); // Assuming here that the functions take no arguments.
std::stack<voidFunctionPointer> instructionSteps; // This is very different from <void*>.
// The latter is merely a stack of void pointers.
One way of calling the top function is this:
voidFunctionPointer functionToCall = instructionSteps.top();
functionToCall();
If you want to do it without an extra declaration, I think this should work. Please correct me if I'm wrong.
instructionSteps.top()();
To build the stack, just use the function name without any trailing parentheses.
instructionSteps.push(step1);
instructionSteps.push(step2);
// ...
Let me first explain what I'm trying to achieve using some pseudo-code (JavaScript).
// Declare our function that takes a callback as as an argument, and calls the callback with true.
B(func) { func(true); }
// Call the function
B(function(bool success) { /* code that uses success */ });
I hope this says it all. If not, please comment on my question so I can write a little more to clarify my issue.
What I want is to have code like this in C++.
I have tried to use lambda functions, but I was unable to specify a parameter type for those.
If your compiler is a fairly recent release (such as Visual Studio 2010 or GCC 4.5), you can use some new features from the new C++ standard, which is currently in ratification and should be published soon.
I don't know what you need to do to enable this in Visual Studio, but it should be well-documented either on MSDN or internal help.
For GCC 4.5, just add the -std=c++0x option to enable the new features.
One of these features is the Lambda syntax:
template <typename F>
void func_with_callback(F f) {
f(true);
}
int main() {
func_with_callback( [](bool t){ if(t) cout << "lambda called" << endl; } );
}
If you don't have access to a modern compiler, you can use techniques such as functors and libraries like boost::lambda, which can perform similarly.
EDIT: Upon reading your question again, it looks like you might be looking for anonymous functions in C++. If that's what you want, unfortunately the language does not support that feature. C++ requires you be a bit more verbose with those sorts of things at present time. If you need more than what boost::lamda is already providing you then you should probably separate it out as a normal function anyway.
In C and C++ this is accomplished using function pointers or functors and templates (C++ only).
For example (using the C++ way (functors))
//Define a functor. A functor is nothing but a class which overloads
//operator(). Inheriting from std::binary_function allows your functor
//to operate cleanly with STL algorithms.
struct MyFunctor : public std::binary_function<int, int, bool>
{
bool operator()(int a, int b) {
return a < b;
};
};
//Define a template which takes a functor type. Your functor should be
//should be passed by value into the target function, and a functor should
//not have internal state, making this copy cheap.
template <typename Func_T>
void MyFunctionUsingACallback(Func_T functor)
{
if (functor(a, b))
//Do something
else
//Do something else
}
//Example usage.
int main()
{
MyFunctionUsingACallback(MyFunctor());
}
Using the C way (function pointers):
//Create a typedef for a function pointer type taking a pair of ints and
//returning a boolean value.
typedef bool (*Functor_T)(int, int);
//An example callback function.
bool MyFunctor(int a, int b)
{
return a < b;
}
//Note that you use the typedef'd function here.
void MyFunctionUsingACallback(Functor_T functor)
{
if (functor(a, b))
//Do something
else
//Do something else
}
//Example usage.
int main()
{
MyFunctionUsingACallback(MyFunctor);
}
Note that you should prefer the C++ way because it will allow the compiler to
make more intelligent decisions with regards to inlining, unless for some reason
you are limited to the C subset.
First of all I have to admit that my programming skills are pretty limited and I took over a (really small) existing C++ OOP project where I try to push my own stuff in. Unfortunately I'm experiencing a problem which goes beyond my knowledge and I hope to find some help here. I'm working with a third party library (which cannot be changed) for grabbing images from a camera and will use some placeholder names here.
The third party library has a function "ThirdPartyGrab" to start a continuous live grab and takes a pointer to a function which will be called every time a new frame arrives. So in a normal C application it goes like this:
ThirdPartyGrab (HookFunction);
"HookFunction" needs to be declared as:
long _stdcall HookFunction (long, long, void*);
or "BUF_HOOK_FUNCTION_PTR" which is declared as
typedef long (_stdcall *HOOK_FUNCTION_PTR) (long, long, void*);
Now I have a C++ application and a class "MyFrameGrabber" which should encapsulate everything I do. So I put in the hook function as a private member like this:
long _stdcall HookFunction (long, long, void*);
Also there is a public void function "StartGrab" in my class which should start the Grab. Inside I try to call:
ThirdPartyGrab (..., HookFunction, ...);
which (not surprisingly) fails. It says that the function call to MyFrameGrabber::HookFunction misses the argument list and I should try to use &MyFrameGrabber::HookFunction to create a pointer instead. However passing "&MyFrameGrabber::HookFunction" instead results in another error that this cannot be converted to BUF_HOOK_FUNCTION_PTR.
After reading through the C++ FAQ function pointers I think I understand the problem but can't make up a solution. I tried to make the hook function static but this also results in a conversion error. I also thought of putting the hook function outside of the class but I need to use class functions inside the hook function. Is there another way or do I need to change my whole concept?
EDIT 14.01.08:
I tested the singleton workaround since I cannot change the third party library and the void pointer is only for data that is used inside the hook function. Unfortunately it didn't worked out of the box like I hoped.... I don't know if the static function needs to be in a separate class so I put it in my "MyFrameGrabber" class:
static MyFrameGrabber& instance()
{
static MyFrameGrabber _instance;
return _instance;
}
long Hook(long, long, void*); // Implementation is in a separate cpp file
In my cpp file I have the call_hook function:
long MFTYPE call_hook(long x, MIL_ID y, void MPTYPE *z)
{
return MyFrameGrabber::instance().Hook(x,y,z);
}
void
MyFrameGrabber::grab ()
{
ThirdPartyGrab(..., call_hook, ...);
}
But this gives me an error in static MatroxFrameGrabber _instance; that no matching standard constructor is found. That's correct because my MyFrameGrabber constructor looks like this:
MyFrameGrabber (void* x,
const std::string &y, int z,
std::string &zz);
I tried to put in an empty constructor MyFrameGrabber(); but this results in a linker error. Should I pass empty parameters to the MyFrameGrabber constructor in the singleton? Or do I need to have a separate Hook Class and if yes how could I access MyFrameGrabber functions? Thanks in advance.
SECOND EDIT 15.01.08:
I applied the changes and it compiles and links now. Unfortunately I cannot test this at runtime yet because it's a DLL and I have no Debug Caller Exe yet and there are other problems during initialization etc. I will mark the post as answer because I'm sure this is the right way to do this.
Your private member method has an implicit this pointer as first argument. If you write that out, it's obvious that the function signatures do not match.
You need to write a static member function, which can be passed as the callback-function to the library. The last argument to the HookFunction, a void*, looks to me very much like a cookie, where one can pass ones own pointer in.
So, all in all, it should be something like this:
class MyClass {
long MyCallback(long, long) {
// implement your callback code here
}
static long __stdcall ThirdPartyGrabCallback(long a, long b, void* self) {
return reinterpret_cast<MyClass*>(self)->MyCallback(a, b);
}
public:
void StartGrab() {
ThirdPartyGrab(..., &MyClass::ThirdPartyGrabCallback, ..., this, ...);
}
};
This of course only works if the void* argument is doing what I said. The position of the this in the ThirdPartyGrab() call should be easy to find when having the complete function signature including the parameter names available.
The reason "&MyFrameGrabber::HookFunction" cannot be converted to a BUF_HOOK_FUNCTION_PTR is that, being a member of the class, it has implicitly as first parameter the "this" pointer, thus you cannot convert a member function to a non-member function: the two signatures look the same but are actually different.
I would declare an interface, defining the function to call, have your class implement it and pass the object itself instead of the callback (you can think of an interface as the object-oriented replacement of a function pointer):
class IHookInterface{
public:
virtual long HookFunction(long, long, void*) = 0;
};
class HookClass : public IHookInterface{
public:
virtual long Hook(long, long, void*) {
// your code here...
}
};
// new definition:
ThirdPartyGrab (..., IHookInterface, ...);
EDIT - other possible solution in case you cannot modify the library: use a singleton rather than a static function.
class HookClass{
public:
static HookClass& instance(){
static HookClass _instance;
return _instance;
}
long Hook(long, long, void*) {
// your code here...
}
};
long call_hook(long x,long y,void * z){
return HookClass::instance().Hook(x,y,z);
}
SECOND EDIT: you might slightly modify the singleton class with an initialization method to call the constructor with the proper parameters, but maybe it is not more elegant than the following solution, which is simpler:
class HookClass{
public:
HookClass(string x,string y...){
}
long Hook(long, long, void*) {
// your code here...
}
};
static HookClass * hook_instance = 0;
long call_hook(long x,long y,void * z){
if (0 != hook_instance){
return hook_instance->Hook(x,y,z);
}
}
int main(){
hook_instance = new HookClass("x","y");
ThirdPartyGrab(..., call_hook, ...);
}