Very basic question about argument with signature void *data - c++

This is very likely an extremely basic question - sorry about that.
I have written an interface in C++ which is powered by a C engine. One of the C-engine functions has the following signature:
static int f(double t, double *y, double *ydot, void *data)
The *data thingy is to pass user data to an ODE solver. Now, in C I would simply create an struct, initialize it with my data, and pass it around. In C++ I want to create a class containing the user data, and pass it as I previously passed the struct. This can be done, as structs are classes.
However, when I try to do it, the following happens:
int.cpp:25: error: no matching function for call to ‘UserData::UserData()’
int.cpp:13: note: candidates are: UserData::UserData(double)
int.cpp:5: note: UserData::UserData(const UserData&)
int.cpp:28: error: ‘void*’ is not a pointer-to-object type
int.cpp:29: error: ‘void*’ is not a pointer-to-object type
My questions are the following:
What does the void *data notation mean?
Why is it complaining that I don't have a constructor with the appropriate signature?
Obviously I am very much a rookie, so I'm sorry if this is very obvious, but I don't even know what terms to use to google the problem (in addition to googling the error itself).
Thanks!
Edit:
I apologize for the vagueness of the previous question. Also, I solved the problem and it was a very stupid mistake.
I had a class containing parameters:
class Data{
// an interface to get parameters
};
and I needed to call a C function with the signature
static int f(double t, ...., void *user_data)
I mistakenly did this:
static int f(double t, ...., void *user_data){
Data *data = (Data*) data; /* this is the stupid mistake */
}
When I meant to do this (now it works):
static int f(double t, ...., void *user_data){
Data *data = (Data*) user_data; /* this is the correction */
}
Thank you all - and I appreciate indicating the correct meaning of void *data.

void *data
means a pointer to any address. It is a non-typesafe way of passing data of arbitrary type. It is a common pattern in C to implement what would be done with a function object in C++. The data parameter is probably not actually used by your ODE solver, but by a callback that you are providing. You and the callback need to know the what data points to, the ODE solver doesn't. The solver just passes the address to the callback function.
As simple example, suppose the library had a function to find the root of a function in a single variable
typedef double (*valuation_function) (double x, void * params);
double find_root(valuation_function fn, double lower, double upper, void* params);
The params function gives you the ability to write a parameterized function. Suppose you wanted to find the root of a line.
struct Line {
double slope;
double intercept;
public:
Line(double s, double i) : slope(s), intercept(i) {}
};
double a_line(double x, void *params) {
Line* line = (Line *)params;
return line->slope * x + line->intercept;
}
You could then call the function find_root for any line.
Line fortyFive(1.0, 0.0);
find_root(a_line, fortyFive);
You can look at the gsl library for more examples.

Related

How to bind a memberfunction to a library callback?

I am searching for a solutiuon to assign a memberfuction Callback to the extLibrary->OnNewFrame where OnNewFrame is a pointer-to-function type.
class Test
{
public:
void init();
void Callback(ImageDataType, int);
private:
};
void Test::init(){
extLibrary=new CameraLib;
extLibrary->OnNewFrame = Test::Callback;
//OnNewFrame is a pointer-to-function type
}
void Test::Callback(ImageDataType data, int n){
doImageProc();
}
If I change the Code above to static void Callback(ImageDataType, int), the code runs fine, but of course I can not access the variables of the Test Class in Callback .
I think I have to init the Class and pass the memberfunction to the lib's pointer-to-function type after, but I don't know how to do that properly.
EDIT
Sorry, this is my first post and I provided wrong and incomplete information. I will try to improve this post as far as I am able to.
To clarify what the library actually needs:
typedef void (__stdcall *GrabNewFrame) (HANDLE h, int i);
//this is the pointer to function definition
...
//after that in the lib-class:
class CameraLib
{
...
public:
GrabNewFrame OnNewFrame;
...
}
OnNewFrame gets called by the lib every time a frame arrives from the camera.
So as far as I know, I have to assign my own void function to OnNewFrame . Without OOP this works like a charm. But with classes I do not get a memberfunction assigned to OnNewFrame ...

Using Boost bisection when the function relies on a class attribute and has additional arguments

I am trying to use the Boost bisection method described here.
I have seen a couple of examples of how to get this to work, e.g. How to use boost bisection?, but I don't understand how to apply these to my particular set-up.
Here is a sketch of some code that illustrates what I am trying to do.
class Model {
double b;
double root;
public:
double func(double x, double c);
void solve(void);
};
double Model::func(double x, double c) {
return (x*x*x + (b*x) + c);
}
void Model::solve(void) {
double c;
b = 2.;
c = 1.;
// root = bisect(func(), from, to, ...);
// where the first argument to func() is what we want to find the root over
// and the second argument to func() is c
}
int main(void) {
Model model;
model.solve();
}
The member function solve() needs to find the root of the member function func(). func() has two important features:
It relies on the class attribute b
It has a second argument c that is determined in solve(). I want to hold this second argument fixed when finding the root
How would I implement the Boost bisection method in this context? This answer seems to suggest that boost::bind might solve part of the problem but I don't understand enough of it to know how to apply it to my problem.

Pass a function of n arguments as function of n-x arguments

This is a very basic question and I'm sure this was answered before, but I don't know what to search for.
Stated I have a function that integrates a mathematical function:
double integrator(double (*func_to_integrate)(double,double));
But my function to integrate is of a type that allows me to manipulate more than two parameters, for example:
double func_to_integrate(double mu, double w0, double x, double y);
So that I can loop over different values of mu and w0 and compare the results of integration.
How can I pass a function like func_to_integrate to integrator?
Greetings
Edit: As alain pointed out in the comments this is partly a duplicate of: How can currying be done in C++?
Is there an elegant solution doing a currying operation on a function pointer?
Given you are able to change the signature of the integrator function, there are several solutions. The basic two directions are
use a general template parameter instead of the function pointer (--where the caller has to be aware of the correct signature to pass), or
use std::function<double(double, double)> as the function argument.
Both alternatives allow you to pass general function objects (functors, lambdas, a std::bind-object, etc.). I'd go with alternative 1. as it usually gives a better performance.
Then you can easily set up a lambda:
double mu = 1.0;
double w0 = 1.0;
auto f = [mu, w0] (double x, double y) { return func_to_integrate(mu, w0, x, y); };
and pass f to your (adusted) integrator routine.
Here is further an alternative if you cannot change the function signature -- as it is often the case for third-party libraries.
I first thought there is no solution in this case, as you can't bind a general functor to a function pointer. But then I encountered the nice idea in this answer (which I slightly adjusted): encode everything in terms of a static std::function variable, then use a static function to call this std::function object. As the static function is just syntactic sugar for a global function, it is possible to set up a function pointer to it:
template <typename Res, typename... Args>
struct function_ptr_helper
{
public:
template<typename function_type>
static auto bind(function_type&& f) { func = std::forward<function_type>(f); }
static auto invoke(Args... args) { return func(args...); }
static auto* ptr() { return &invoke; }
private:
static std::function<Res(Args ...)> func;
};
template <typename Res, typename... Args>
std::function<Res(Args ...)> function_ptr_helper<Res, Args...>::func;
template <typename Res, typename ... Args>
auto* get_function_ptr(std::function<Res(Args...)> f)
{
using type = function_ptr_helper<Res, Args...>;
type::bind(std::move(f));
return type::ptr();
}
DEMO
You can use it as
double mu = 1.0;
double w0 = 1.0;
std::function<double(double, double)> f
= [mu, w0] (double x, double y) { return func_to_integrate(mu, w0, x, y); };
integrator(get_function_ptr(f));
Be aware, however, that you are dealing with global variables here. This often works, but sometimes might lead to subtle errors (for example when you call get_function_ptr more than once in a single expression).
How can I pass a function like func_to_integrate to integrator?
Seems very easy to fix. Just add two more arguments to your pointer function signature.
double integrator(double (*func_to_integrate)(double,double,double,double));
As previous comments point out the most elegant solution would be using bind and or lambda. A nice solution would be an adapter design pattern class wrapper, where mu and w0 become class members.
class IntegratorAdaptor {
private:
double _mu, double _w0;
public:
IntegratorAdapter(double arg_mu, double arg_w0)
: _mu(arg_mu), _w0(arg_w0) { }
double twoArgIntegrator( double x, double y )
{ return func_to_intergrate( _mu, _w0, x, y ); }
};
Construction of this class is very low overhead, so I made the members immutable. I didn't come up with very good names for the class and functions, you should put more thought into those names than I did.
Most answers I've seen for this kind of question rely on std::function and/or C++ templates. I wanted to share an alternate solution which may be less general, but to me is simpler. It doesn't use std::function or templates---in fact, it doesn't use any libraries at all.
The idea is that instead of passing around a function pointer, you pass around an object that implements a particular 'interface'. In this example,
double integrator(double (*func_to_integrate)(double,double))
becomes
double integrator(Integratable func_to_integrate)
where Integratable is an 'interface' (abstract base class) defined as
class Integratable {
public:
virtual double compute(double x, double y) = 0; // pure virtual function
}
We can then make func_to_integrate into an instance of this class, with extra members for the additional parameters:
class SomeClassName : public Integratable {
public:
double compute(double x, double y);
double mu;
double w0;
}
SomeClassName func_to_integrate;
To test several values of mu and w0 in a loop:
for(double mu : mus) {
for(double w0 : w0s) {
func_to_integrate.mu = mu;
func_to_integrate.w0 = w0;
integrator(func_to_integrate);
}
}
Of course, we have to modify integrator so that instead of calling a function pointer, it calls the compute() method on the object passed to it, but this is trivial (assuming you can change the signature of integrator, which is probably required for any possible solution to this problem).
I like this solution because it avoids some of C++'s more heavyweight features and libraries. However, it certainly is less general than many of the other solutions that are often suggested for partial application in C++. For OP I believe this solution is an elegant fit for the given use case.

Create a function from another one

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 &target;
}
};
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.

Function pointer to class member function problems

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, ...);
}