Hi,

I have been trying for hours to solve this problem. I have attached below a very simplified version of my actual code. The constraints are:
1) the function "lib" cannot have its signature changed, as it is part of a library.
2) the pointer attribute "funcPtr" cannot be static as different instances of "myClass" will not share this variable. The function "wrapperFunc" can be static if necessary.
3) The goal here is that the user should not have to write the function that will be called from the library "lib" with the following signature : "int (*func)(vector<float> v)" but should write its function with the signature "int (*func)(float* v, int n)".

The actual problem lies in the method "libWrapper". I understand that my reasons to do this might seem irrelevant, but those constraints cannot be bypassed. Thank you in advance for your assistance !

#include <iostream>
using std::cout;
using std::endl;
#include <vector>
using std::vector;

// Function Prototypes
int myFunc(float* v, int n);
int lib( int (*fct)(vector<float> v) , vector<float> v);

class myClass {
  private:
	int (*funcPtr)(float* v, int n);
	
	static int wrapperFunc(vector<float> v) {
		funcPtr(&v[0], v.size());
	}
	
  public:
	
	myClass() : funcPtr(0) {}
	
	void setFunc( int (*fct)(float* v, int n) ) {
		funcPtr = fct;
	}
	
       // Problem lies in this method
	void libWrapper(vector<float> v) {
		lib( &wrapperFunc , v);
		//lib( reinterpret_cast<int (*)(vector<float> v)>(wrapperFunc) , v);
		//lib( (int (*)(vector<float> v))(&(this->wrapperFunc)) , v);

		//wrapperFunc(v);  // works obviously, but don't want to/cannot use this way
	}
};

int main() {
	
	myClass obj;
	obj.setFunc(&myFunc);
	vector<float> v;
	v.push_back(0.2);
	v.push_back(-1.36);
	obj.libWrapper(v);  // Problem is here
}

int myFunc(float* v, int n) {
	for (int i=0; i<n; ++i) {
		cout << "v[" << i << "]**2 = " << v[i]*v[i] << endl;
	}
}

int lib( int (*fct)(vector<float> v) , vector<float> v) {
	cout << "Inside lib ..." << endl;
	fct(v);
}

Recommended Answers

All 2 Replies

Does anyone have an idea about it ?
Thanks.

Here is a function pointer tutorial
http://www.newty.de/fpt/fpt.html

> I have attached below a very simplified version of my actual code.
A simplified version that actually compiles would help.
Like what is fct() on line 55?

Sure, you have to leave a few lines commented out where the trouble is, but if we fix that, then it should work.

commented: Great link. +9
Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.