This might be a stupid simple thing I'm overlooking, but I am setting values in the Data::Data(char *DataType...) function as they are being passed in, and as I hover over them, they are setting fine (the variables type, material, ID, unit, reading when hovered over are what they should be).
However, when the getData function is called below, when I hover over the pointer arguments(*type, *materials.. etc) they are set to random strings like directory names and file names. I'm not sure why this is happening, because when the variables are being set above they are right.
I've included the header and implementation files for the Data class, where all of these functions are defined, but If I need include where they are being called please let me know, the only reason I didn't is because the calls are short and files are filled with other irrelevant stuff. Thanks
Data.cpp
#include "Data.hpp"
Sensor::Sensor(char *DataType, char *Material, int ID, char *Sensor, double Min, double Max) {
strcpy(type, Type);
strcpy(material, Material);
ID = SIDs;
strcpy(unit, Units);
max = Maxs;
min = Mins;
}
Sensor::Sensor() {}
double Data::generateData() {
reading = min + (rand() % (int)(max - min + 1));
return reading;
}
void Data::getData(char *type, char *material, int *ID, char *unit, double *reading) {
return;
}
Data::~Data(){}
Data.hpp
#ifndef Data_hpp
#define Data_hpp
#include
#include
#include
using namespace std;
class Data
{
public:
Data();
Data(char *Type, char *Material, int ID, char *Unit, double Min, double Max);
~Data();
void getData(char *type, char *material, int *ID, char *unit, double *reading);
private:
char type[32];
char material[32];
int ID;
int reading;
char unit[32];
double min;
double max;
double generateData();
};
#endif
Your implementation of Sensor::getData does not do what you think it does.
Let's look at this class:
class Foo
{
void getX(int* x)
{
}
int* x;
};
Within getX, the parameter x hides the member x of the same name. This function does literally nothing: A user passes a pointer to an int, which gets the name x in this function. The member is not automatically copied into there (which would be surprising, since you could name the parameter anything else). If you want to do that, you must do it explicitly:
void getX(int* x)
{
*x = *this->x; // Pointed-to value is copied
//x = this->x; // Pointer is copied
}
If you do not set the function parameter to anything, the pointer will keep pointing to random garbage in memory, which is what you are seeing in your debugger.
The more common way to denote "this parameter will be changed/set by this function" is passing a reference:
class Foo
{
void get(char*& x, int*& y, double& z)
{
x = this->x; // Now both parameter and member point to the same location.
y = this->y; // Now both parameter and member point to the same location.
z = this->z;
}
char x[32];
int* y;
double z;
};
Or, if you don't want to copy the pointers but the pointed-to values:
void get(char* x, int* y, double& z)
{
strcopy(x, this->x);
*y = *this->y;
z = this->z;
}
(PS: I recommend using std::string instead of char arrays if your use case allows for it.)
You uninitialized arguments are set to random garbage no matter if you call getData() or not. Try to print them out without calling getData() and see.
I'm very new to pointers so please bear with me...
My code defines a function for the multiplication of two matrices (matrixMultiplication). I have then defined a function pointer to this function.
#include <iostream>
void matrixMultiplication (const double A[3][3], const double B[3][3], double output[3][3])
{
int i, j, k;
for (i=0;i<3;i++)
{
for(j=0;j<3;j++)
{
for(k=0;k<3;k++)
{
output[i][j]+=A[i][k]*B[k][j];
}
}
}
}
double (*matrixMultiplication (const double (*left)[3], const double (*right)[3]))[3]
{
double output[3][3];
matrixMultiplication(left, right, output);
}
int main ()
{
using namespace std;
double A[3][3]={{1,1,1},{1,1,1},{1,1,1}};
double B[3][3]={{1,1,1},{1,1,1},{1,1,1}};
cout<<"The function returns..."<<endl;
double print[3][3]=matrixMultiplication(A,B);
int i, j;
for (i=0;i<3;i++)
{
for (j=0;j<3;j++)
{
cout<<print[i][j]<<"\t";
}
cout<<"\n";
}
return 0;
}
What I want to do is output the array given by the pointer function, *matrixMultiplication, using a for loop (just for aesthetic purposes). I have played around with the code and ended up with initialiser or segmentation (11) errors. I feel like I'm missing something blatantly obvious given I'm new to C++...
Any ideas would be most welcome!
The problem is with:
double (*matrixMultiplication (const double (*left)[3], const double (*right)[3]))[3]
{
double output[3][3];
matrixMultiplication(left, right, output);
}
I don't know what it is and neither does my compiler! ;)
Using functional, a matrixMultiplication function type can be defined and used, like so:
#include <functional> // or <tr1/functional>
// type
typedef function<void (const double[3][3], const double[3][3], double[3][3])> MatrixFunction;
// instance
MatrixFunction matrixFunctionPtr(&matrixMultiplication);
// call
matrixFunctionPtr(A,B,print);
Note: you also need to declare your output array double print[3][3]; * before* you call the matrixMultiplication function...
You have a function:
void matrixMultiplication (const double A[3][3], const double B[3][3], double output[3][3])
{
...
}
This function works. It takes three arrays as arguments (which is to say it takes three pointers-- this is a subtle point, and I don't think it's a good exercise for a beginner because it clouds the distinction between passing by value and passing by reference -- but never mind that for now) and returns void (i.e. nothing), and . Now you want to construct a function pointer that points to this function. But this:
double (*matrixMultiplication (const double (*left)[3], const double (*right)[3]))[3]
{
...
}
is not a function pointer; it's a function that returns a pointer to an array of double, but it has some internal errors (and don't even worry about what it takes as arguments for now).
Let's do a simpler example first:
double foo(int n) // function
{
return(3);
}
int main()
{
double (*bar)(int); // function pointer
bar = &foo;
double z = (*bar)(5);
cout << z << endl;
return(0);
}
Now that we see how function pointers work, we apply one to matrixMultiplication:
void (*matFP)(const double A[3][3], const double B[3][3], double output[3][3]);
matFP = &matrixMultiplication;
double C[3][3];
(*matFP)(A,B,C);
Abstract
I have a class that stores a optimization problem and runs a solver on that problem.
If the solver fails I want to consider a sub-problem and solve using the same solver (and class).
Introduction
An optimization problem is essencially a lot of (mathematical) functions. The problem functions are defined outside the class, but the sub-problem functions are defined inside the class, so they have different types (e.g. void (*) and void (MyClass::*).
At first I thought that I could cast the member function to the non-member pointer-to-function type, but I found out that I cannot. So I'm searching for some other way.
Example Code
An example code to simulate my issue:
#include <iostream>
using namespace std;
typedef void (*ftype) (int, double);
// Suppose foo is from another file. Can't change the definition
void foo (int n, double x) {
cout << "foo: " << n*x << endl;
}
class TheClass {
private:
double value;
ftype m_function;
void print (int n, double x) {
m_function(size*n, value*x);
}
public:
static int size;
TheClass () : value(1.2), m_function(0) { size++; }
void set_function (ftype p) { m_function = p; }
void call_function() {
if (m_function) m_function(size, value);
}
void call_ok_function() {
TheClass ok_class;
ok_class.set_function(foo);
ok_class.call_function();
}
void call_nasty_function() {
TheClass nasty_class;
// nasty_class.set_function(print);
// nasty_class.set_function(&TheClass::print);
nasty_class.call_function();
}
};
int TheClass::size = 0;
int main () {
TheClass one_class;
one_class.set_function(foo);
one_class.call_function();
one_class.call_ok_function();
one_class.call_nasty_function();
}
As the example suggests, the member function can't be static. Also, I can't redefine the original problem function to receive an object.
Thanks for any help.
Edit
I forgot to mention. I tried changing to std::function, but my original function has more than 10 arguments (It is a Fortran subroutine).
Solution
I made the change to std::function and std::bind as suggested, but did not went for the redesign of a function with more 10 arguments. I decided to create an intermediate function. The following code illustrates what I did, but with fewer variables. Thanks to all.
#include <iostream>
#include <boost/tr1/functional.hpp>
using namespace std;
class TheClass;
typedef tr1::function<void(int *, double *, double *, double *)> ftype;
// Suppose foo is from another file. Can't change the definition
void foo (int n, int m, double *A, double *x, double *b) {
// Performs matrix vector multiplication x = A*b, where
// A is m x n
}
void foo_wrapper (int DIM[], double *A, double *x, double *b) {
foo(DIM[0], DIM[1], A, x, b);
}
class TheClass {
private:
ftype m_function;
void my_function (int DIM[], double *A, double *x, double *b) {
// Change something before performing MV mult.
m_function(DIM, A, x, b);
}
public:
void set_function (ftype p) { m_function = p; }
void call_function() {
int DIM[2] = {2,2};
if (m_function) m_function(DIM, 0, 0, 0);
}
void call_nasty_function() {
TheClass nasty_class;
ftype f = tr1::bind(&TheClass::my_function, this, _1, _2, _3, _4);
nasty_class.set_function(f);
nasty_class.call_function();
}
};
int main () {
TheClass one_class;
one_class.set_function(foo_wrapper);
one_class.call_function();
one_class.call_nasty_function();
}
PS. Creating a std::function with more than 10 variables seemed possible (compiled, but I didn't test) with
#define BOOST_FUNCTION_NUM_ARGS 15
#include <boost/function/detail/maybe_include.hpp>
#undef BOOST_FUNCTION_NUM_ARGS
But creating a std::bind for more than 10 arguments does not seem as easy.
std::function, std::bind, and lambdas are what you are looking for. In short, function pointers are very bad things and should be burned in fire. In long, std::function can store any function object which can be called with the correct signature, and you can use std::bind or a lambda to generate a function object that calls your member function quickly and easily.
Edit: Then you will just have to roll your own std::function equivalent that supports more than 10 arguments.
i can't understand following defining pointer variable. can you help me?
double(*)(double *) foo;
note : sory, i edit name of variable func to foo.
This is not valid C. Perhaps you mean this:
double(*func)(double *);
which declares func as a pointer to a function that takes a pointer-to-double, and returns a double.
You can use http://cdecl.org for this sort of thing.
Try this (tested):
// functions that take double * and return double
double dfunc(double *d) { return (*d) * 2.0; }
double tfunc(double *d) { return (*d) * 3.0; }
int main()
{
double val = 3.0;
double // 3. the function returns double
(*pFunc) // 1. it's a pointer to a function
(double *); // 2. the function takes double *
pFunc = dfunc;
printf("%f\n", pFunc(&val)); // calls dfunc()
pFunc = tfunc;
printf("%f\n", pFunc(&val)); // calls tfunc()
}
Output:
6.000000
9.000000
it's a pointer to a function returning double having a parameter of type pointer to double, if you correct the variable declaration since as it stands its just incorrect correct syntax would be double (*foo) (double*)
uses are polymorphism by being able to replace a function:
struct memory_manager{
void*(*getmem)(size_t);
void(*freemem)(void*);
}mem_man;
void* always_fail(size_t){return 0;}
void* myalloc(size_t s){
void* p=mem_man.get_mem(s);
if(p) return p;
mem_man.getmem=always_fail;
return 0;
}
void myfree(void* p){
if(p) freemem(p);
}
it's not really the c++-way i geuss, since for most purposes inheritance and virtual functions offer a better solution, but if you're restricted to c, then you can use this technique to simulate virtual functions.
I have a problem using a very complicated C function in a C++ class (rewriting the C function is not an option). C function:
typedef void (*integrand) (unsigned ndim, const double* x, void* fdata,
unsigned fdim, double* fval);
// This one:
int adapt_integrate(unsigned fdim, integrand f, void* fdata,
unsigned dim, const double* xmin, const double* xmax,
unsigned maxEval, double reqAbsError, double reqRelError,
double* val, double* err);
I need to supply a void function of type integrand myself, and adapt_integrate will calculate the n-dimensional integral. The code in calcTripleIntegral (below) works as a standalone function if func is a standalone function).
I want to pass a (non-static!) class member function as the integrand, as this can be easily overloaded etc...
class myIntegrator
{
public:
double calcTripleIntegral( double x, double Q2, std::tr1::function<integrand> &func ) const
{
//...declare val, err, xMin, xMax and input(x,Q2) ...//
adapt_integrate( 1, func, input,
3, xMin, xMax,
0, 0, 1e-4,
&val, &err);
return val;
}
double integrandF2( unsigned ndim, const double *x, void *, // no matter what's inside
unsigned fdim, double *fval) const; // this qualifies as an integrand if it were not a class member
double getValue( double x, double Q2 ) const
{
std::tr1::function<integrand> func(std::tr1::bind(&myIntegrator::integrandF2, *this);
return calcTripleIntegral(x,Q2,func);
}
}
On GCC 4.4.5 (prerelease), this gives me:
error: variable 'std::tr1::function func' has initializer but incomplete type
EDIT:What is the error in my code? I have now tried compiling with GCC 4.4, 4.5 and 4.6, all resulting in the same error. Either no work has been done on this, or I did something wrong /EDIT
Thanks very much! If I'm not clear enough, I'll gladly elaborate.
PS: Could I work around this without tr1 stuff by using a function pointer to a function defined somewhere in myIntegrator.cpp?
FINAL UPDATE: ok, I was mistaken in thinking TR1 provided a one/two-line solution for this. Bummer. I'm "converting" my classes to namespaces and copypasting the function declarations. I only need one base class and one subclass which reimplemented the interface. C function pointer + C++ class = bad news for me.
Thanks anyways for all the answers, you've shown me some dark corners of C++ ;)
If you are just trying to pass a member function into a c-style callback, you can do that with out using std::t1::bind or std::tr1::function.
class myIntegrator
{
public:
// getValue is no longer const. but integrandF2 wasn't changed
double getValue( double x, double Q2 )
{
m_x = x;
m_Q2 = Q2;
// these could be members if they need to change
const double xMin[3] = {0.0};
const double xMax[3] = {1.0,1.0,1.0};
const unsigned maxEval = 0;
double reqAbsError = 0.0;
double reqRelError = 1e-4;
double val;
adapt_integrate( 1, &myIntegrator::fancy_integrand,
reinterpret_cast<void*>(this),
3, xMin, xMax,
maxEval, reqAbsError, reqRelError,
&val, &m_err);
return val;
}
double get_error()
{ return m_error; }
private:
// use m_x and m_Q2 internally
// I removed the unused void* parameter
double integrandF2( unsigned ndim, const double *x,
unsigned fdim, double *fval) const;
static double fancy_integrand( unsigned ndim, const double* x, void* this_ptr,
unsigned fdim, double* fval)
{
myIntegrator& self = reinterpret_cast<myIntegrator*>(this_ptr);
self.integrateF2(ndim,x,fdim,fval);
}
double m_x
double m_Q2;
double m_err;
};
You have three problems... first you want a std::tr1::function<R (Args..)>, but yours boils down to std::tr1::function<R (*)(Args...)> - so you need two typedefs:
typedef void (integrand) (unsigned ndim, const double *x, void *,
unsigned fdim, double *fval);
typedef integrand* integrand_ptr;
... so the first allows you a compilable function<integrand>. adapt_integrate has to be fixed accordingly:
int adapt_integrate(unsigned fdim, integrand_ptr f, ...);
Next your bind syntax is off, it should be:
std::tr1::bind(&myIntegrator::integrandF2, *this, _1, _2, _3, _4, _5);
The remaining problem is that tr1::function<T> isn't convertible to a function pointer, so you would have to go through a wrapper function, using the void* fdata argument to pass the context. E.g. something like:
extern "C" void integrand_helper (unsigned ndim, const double *x, void* data,
unsigned fdim, double *fval)
{
typedef std::tr1::function<integrand> Functor;
Functor& f = *static_cast<Functor*>(data);
f(ndim, x, data, fdim, fval);
}
// ...
adapt_integrate(1, &integrand_helper, &func, ...);
This is of course assuming that the void* parameter is passed through to the function, if not it would get ugly.
On the other hand, if void* fdata allows to pass context, all that tr1::function stuff is unnecessary and you could just go directly through a trampoline function - just pass this through as the context argument:
extern "C" void integrand_helper (unsigned ndim, const double *x, void* data,
unsigned fdim, double *fval)
{
static_cast<myIntegrator*>(data)->integrandF2(ndim, ...);
}
// ...
adapt_integrate(1, &integrand_helper, this, ...);
Since std::tr1::bind and c-style function pointers don't get along, try this instead. It will work, except that myIntegrator::getValue is not longer thread-safe. If calcTripleIntegral were removed from the interface, this would be even simpler and wouldn't need to use std::tr1::bind or std::tr1::function.
class myIntegrator
{
public:
double getValue( double x, double Q2 ) const
{
return calcTripleIntegral(x,Q2,std::tr1::bind(&Integrator::integrandF2,this));
}
double calcTripleIntegral( double x, double Q2, const std::tr1::function<integrand>& func ) const
{
assert( s_integrator == NULL );
s_integrator = this;
m_integrand = func;
//...declare val, err, xMin, xMax and input(x,Q2) ...//
adapt_integrate( 1, &myIntegrator::fancy_integrand, input,
3, xMin, xMax,
0, 0, 1e-4,
&val, &err);
assert( s_integrator == this);
s_integrator = NULL;
return val;
}
private:
double integrandF2( unsigned ndim, const double *x, void *,
unsigned fdim, double *fval) const;
static double fancy_integrand( unsigned ndim, const double* x, void* input,
unsigned fdim, double* fval)
{
s_integrator->integrateF2(ndim,x,input,fdim,fval);
}
std::tr1::function<integrand> m_integrand;
static const myIntegrator* s_integrator;
};
I want to pass a (non-static!) class member function as the integrand...
You can't. If you search SO for using member functions as callbacks you'll be bound to find useful information including the fact that what you're trying to do, the direct approach anyway, is not possible.
Edit: BTW, one of the problems in your code (there's more of course since what you're trying to do is simply not possible) is that you've passed a function pointer type to function<> when what it expects is a signature. The function template is implemented something like so:
template < typename Signature >
struct function;
// for each possible number of arguments:
template < typename R, typename Arg1, typename Arg2 >
struct function<R(Arg1,Arg2)>
{
... body ...
};
As you can see, passing a function pointer to this kind of thing is simply not going to be understood by the compiler. It's going to try to instantiate the forward declaration and get nowhere. This is of course what the compiler error you're getting means but it doesn't address your fundamental problem, which is that what you're doing will never work.
In a fully C++0x compiler this can be done differently but boost::function and the MSVC one has to be like this. Furthermore, the C++0x version is going to have the same problem that you currently are facing.
Making the assumption that the C-API allows passing a type-agnostic (in the sense that the C-API function doesn't have to know its type but relies on the callback function to know what it requires) context parameter (this is usually the case with callback functions; in this case I suspect the fdata parameter to be something along these lines), pass the function object as part of this context parameter.
It should then look something like this:
#include <iostream>
#include <tr1/functional>
typedef void (*callback_function_t)(void *input, int arg);
struct data_type {
int x;
};
struct context_type {
std::tr1::function<void(data_type const &, int)> func;
data_type data;
};
void callback(data_type const&data, int x) {
std::cout << data.x << ", " << x << std::endl;
}
void callback_relay(void *context, int x) {
context_type const *ctxt = reinterpret_cast<context_type const*>(context);
ctxt->func(ctxt->data, x);
}
void call_callback(callback_function_t func, void *context, int x) {
func(context, x);
}
int main() {
context_type ctxt = { callback, { 1 } };
call_callback(callback_relay, &ctxt, 2);
}
Where call_callback is the C-API function. This way, you can assign anything you want that supports function call syntax to context_type::func, including std::tr1::bind expressions. Also, even though (I feel morally obligated to mention this) it is not, strictly speaking, defined in the standard that calling conventions for C and C++ functions are the same, in practice you could make context_type a class template and callback_relay a function template to make context_type::data more flexible and pass anything you like this way.
That error message makes it sound like you're missing an include for one of the types involved. At least try double-checking your integrand and tr1 includes?
bind works a bit different than you assume I think. You either need to provide a value, or a placeholder for every argument.
For your example this boils down to (with placeholders)
std::tr1::function<integrand> func(std::tr1::bind(&myIntegrator::integrandF2, *this, _1, _2, _3, _4, _5));
Since you're binding a member function, you got an extra (implicit) argument, i.e. the object you call the member function on, so you have six.
For the first you bind the this object, for the other arguments you simply pass placeholders.
On a side note, your member function returns double, while the function declaration returns void.
(for the record, I'm still using an older compiler with little tr1 support, so I only have bind and function experience from using boost, maybe things changed a little for tr1...)