I am porting assembly code to C++ and I have some problems porting a portion of it.
I have a pointer declared as:
void* function;
and it is pointing to a function call:
void* function = getfunction(lib, fname);
I have a inline assembly code which I have to migrate to C++:
__asm { call function }
How to call this pointer in C++?
Please note that the arguments lib and fname are of type void*.
And void* function points to value returned by getfunction().
In what follows, I am assuming that the entire function call is encapsulated by
__asm { call function }
In which case this is a function pointer that can be declared like this:
void (*function)(void);
The __asm block does not push parameters onto the stack. Therefore the parameter list is empty. And the __asm block does not extract a return value. So the function has void return type.
You assign to the function pointer in just the same way:
function = getfunction(lib, fname);
And you call it like this:
function();
Look at the following example :
// ptrFunc is the name of the pointer to the getFunction
void* (*ptrFunc)(void*, void*) = &getfunction;
// ... Declaring whatever lib and fname are
// Now call the actual function by using a pointer to it
ptrFunc(lib, fname);
// Another form of how to call getFunc might be :
(*ptrFunc)(lib, fname);
Also, you can pass function pointers to another function such as :
void *getFunction(void* lib, void* fname)
{
// Whatever
}
void myFunction( void* (*ptrFunc)(void*, void*) )
{
// void *lib = something;
// void *fname = something else;
ptrFunc(lib, fname);
}
int main()
{
void* (*ptrFunc)(void*, void*) = &getfunction;
// Passing the actual function pointer to another function
myFunction(ptrfunc);
}
Related
I am trying to create a program which saves the function pointer of a member function to an array. The program then takes the function pointer from that array and calls the function said pointer points to. This works as long as the member function used does not have any arguments. When I give it arguments the following error occurs in Visual Studio 2017:
Run-Time Check Failure #0 - The value of ESP was not properly saved across a function call. This is usually a result of calling a function declared with one calling convention with a function pointer declared with a different calling convention.
My code is:
typedef uint8_t byte;
template<typename T>
class Test
{
public:
void FuncTest(byte* data)
{
cout << (T)(0.0625f) << endl;
}
};
typedef Test<float> fTest;
typedef Test<long long> lTest;
int main()
{
byte data[1024];
{
void (fTest::*ffp)(byte*) = &fTest::FuncTest;
//void (lTest::*lfp)(byte*) = &lTest::FuncTest;
printf("%p\n", ffp);
memcpy(&data[0], (int64*)&ffp, sizeof(int64));
}
{
int64 pData;
memcpy(&pData, &data[0], sizeof(int64));
void(*func_pointer)(byte*) = (void(*) (byte*))(pData);
printf("%p\n", pData);
func_pointer(nullptr);
}
}
If anyone could help, it would be greatly appreciated.
Ignoring the storage in an array your code is essentially:
void (Test::*ffp)(byte*) = &fTest::FuncTest;
void* pData = (void*)ffp;
void(*func_pointer)(byte*) = (void(*) (byte*))(pData);
func_pointer(nullptr);
The type of ffp is essentially (although not exactly due to differing calling conventions) void (fTest*, byte*) which doesn't match the type of func_pointer.
The solution to this is to use std::function with with either std::bind or lambdas to convert the function signatures. e.g.:
std::vector<std::function<void(byte*)>> functions;
fTest test;
functions.push_back([=](byte* data){ test.FuncTest(data); });
functions.front()(nullptr);
So I started to develope an OpenCV program and the thing is that I don't know what this segment of code do in the whole context. Below is an abstract version of the whole code.
class foo{
private:
friend void callBack(void *param);
void draw(void);
public:
void func(void);
void update(void);
}
void callBack(void *param){
foo *context = static_cast<foo*>(param);
if(context){
context->draw();
}
}
foo::foo(std::string windowName){
cv::namedWindow(windowName, frameSize.width, frameSize.height);
cv::resizeWindow(windowName, frameSize.width, frameSize.height);
cv::setOpenGlContext(windowName);
cv::setOpenGlDrawCallback(windowName, callBack, this);
}
void foo::func(void){
cv::updateWindow(m_windowName);
}
void draw(void){
//implementation shows here!!
}
You don't have to explain all the code here. All I need to know is the part where static casting happens. What does it do? Why does a person who implements the code write it this way?
As you can see from the documentation of cv::setOpenGlDrawCallback
The signature is:
void cv::setOpenGlDrawCallback(const String& winname,
OpenGlDrawCallback onOpenGlDraw,
void* userdata = 0
)
The OpenGLDrawCallback is a function pointer of type void (void* arg): where arg is any pointer type you pass to it. In this case, OpenCV actually passes userdata to it. See How do function pointers in C work? (still applicable to C++)
cv::setOpenGlDrawCallback(windowName, callBack, this);
In your code, passing this implicitly converted (a copy of the pointer) it to void* and held by userdata . And and callback is called to draw on your frame
All I need to know is the part where static casting happens. What does
it do? Why does a person who implements the code write it this way?
void callBack(void *param){
foo *context = static_cast<foo*>(param);
if(context){
context->draw();
}
}
The casting converts the void pointer, param to an object of type foo. it basically gets back the semantics of this that was casted when you passed it as a void pointer.
This question already has answers here:
pthread function from a class
(9 answers)
Closed 9 years ago.
I have a class named qwerty and a function called compute_ans inside it which takes a void pointer and returns a void pointer. Now when I try to compile, the following statement throws an error
pthread_create (thread_a, NULL, compute_ans, (void*) struct_left);
The definition of the function is void* compute_ans (void* struct_input)
The error is
cannot convert ‘qwerty::compute_ans’ from type ‘void* (qwerty::)(void*)’ to type ‘void* ()(void)’*
You cannot convert a pointer to a non-static member function to a pointer to function, C++ does not allow it. The reason is that member functions take an implicit this pointer as a parameter. Essentially this changes the signature of your function to be something like void* compute_ans(qwerty*, void*). In order to pass the function to pthread_create you need to make the member function static.
class qwerty
{
public:
// ... other member functions and variables ...
// thread start function
static void* compute_ans(void*);
};
If you cannot make this a static member function you will need to pass a pointer to a qwerty object to the thread start function. Looking at the code in your question you also need to pass additional data to the thread function. To do this you can use an additional data structure that contains all the necessary data and pass a pointer to that instead.
class qwerty; // forward declaration
// Structure passed to pthread_create and our helper function
struct thread_data
{
qwerty* qptr; // pointer to qwerty object
void* data; // pointer to other data. change void to your data type.
};
class qwerty
{
public:
// thread start function
static void* start_compute_ans(void* param)
{
// get a pointer to the thread data
thread_data* tdata = static_cast<thread_data*>(param);
// Call the real compute_ans
tdata->qptr->compute_ans(tdata->data);
// Delete the data (use an appropriate smart pointer if possible)
delete tdata;
return NULL;
}
// the real
void compute_ans(void*)
{
// do stuff here
}
};
// Create our thread startup data
thread_data* tdata = new thread_data();
tdata->qptr = qwerty_pointer;
tdata->data = struct_left;
// start the thread data
pthread_create (thread_a, NULL, &qwerty::start_compute_ans, tdata);
You can find the answer here.
You should use static functions to pass to pthread.
class qwerty
{
public:
void compute_ans(void)
{
std::cout << "Compute result!" << std::endl;
return
}
static void hello_helper(void *context)
{
return ((qwerty *)context)->compute_answer();
}
};
...
qwerty c;
pthread_t t;
pthread_create(&t, NULL, &qwerty::hello_helper, &c);
I will like to know, how to make a function where I define a function. And then I can call the defined function. Let me try with a example.
void funcToCall() {
std::cout<<"Hello World"<<std::endl;
}
void setFuncToCall(void func) {
//Define some variable with func
}
void testFuncCall() {
//Call function that has been defined in the setFuncToCall
}
setFuncToCall(funcToCall()); //Set function to call
testFuncCall(); //Call the function that has been defined
I Hope that you understand what I am trying to do here. But I don't know how to bring It down to the right code :-)
You need a function pointer. It's easier to work with function pointers if you typedef them first.
typedef void (*FuncToCallType)();
FuncToCallType globalFunction; // a variable that points to a function
void setFuncToCall(FuncToCallType func) {
globalFunction = func;
}
void testFuncCall() {
globalFunction();
}
setFuncToCall( funcToCall ); //Set function to call,NOTE: no parentheses - just the name
testFuncCall(); //Call the function that has been defined
As other answers have suggested you can use objects like functions, too. But this requires operator overloading (even if it remains hidden from you) and is typically used with templates.
It gives more flexibility (you can set some state to the object before passing it to the function and the object's operator() can use that state) but in your case function pointers may be just as good.
What you want to use is a callback, and is has been answered her : Callback functions in c++
I would advise you to use std::tr1::function ( generalized callback )
C syntax for function pointers is a bit weird, but here we go:
// this is a global variable to hold a function pointer of type: void (*)(void)
static void (*funcp)(void);
// you can typedef it like this:
//typedef void (*func_t)(void);
// - now `func_t` is a type of a pointer to a function void -> void
// here `func` is the name of the argument of type `func_t`
void setFuncToCall(void (*func)(void)) {
// or just: void setFuncToCall(func_t func) {
//Define some variable with func
...
funcp = func;
}
void testFuncCall(void) {
//Call function that has been defined in the setFuncToCall
funcp();
}
setFuncToCall(funcToCall); // without () !
testFuncCall();
I would like someone to shed some light this code snippet, which confuses me.
//-------------------------------------------------------------------------------
// 3.5 Example B: Callback to member function using a global variable
// Task: The function 'DoItB' does something that implies a callback to
// the member function 'Display'. Therefore the wrapper-function
// 'Wrapper_To_Call_Display is used.
#include <iostream.h> // due to: cout
void* pt2Object; // global variable which points to an arbitrary object
class TClassB
{
public:
void Display(const char* text) { cout << text << endl; };
static void Wrapper_To_Call_Display(char* text);
/* more of TClassB */
};
// static wrapper-function to be able to callback the member function Display()
void TClassB::Wrapper_To_Call_Display(char* string)
{
// explicitly cast global variable <pt2Object> to a pointer to TClassB
// warning: <pt2Object> MUST point to an appropriate object!
TClassB* mySelf = (TClassB*) pt2Object;
// call member
mySelf->Display(string);
}
// function does something that implies a callback
// note: of course this function can also be a member function
void DoItB(void (*pt2Function)(char* text))
{
/* do something */
pt2Function("hi, i'm calling back using a global ;-)"); // make callback
}
// execute example code
void Callback_Using_Global()
{
// 1. instantiate object of TClassB
TClassB objB;
// 2. assign global variable which is used in the static wrapper function
// important: never forget to do this!!
pt2Object = (void*) &objB;
// 3. call 'DoItB' for <objB>
DoItB(TClassB::Wrapper_To_Call_Display);
}
Question 1: Regarding this function call:
DoItB(TClassB::Wrapper_To_Call_Display)
Why does Wrapper_To_Call_Display not take any arguments, although it is supposed to take a char* argument according to its declaration?
Question 2: DoItB is declared as
void DoItB(void (*pt2Function)(char* text))
What I’ve understood so far is that DoItB takes a function pointer as argument, but why does the function call DoItB(TClassB::Wrapper_To_Call_Display) take TClassB::Wrapper_To_Call_Display as argument even tough it’s not a pointer?
Thanx in advance
Source of code snippet: http://www.newty.de/fpt/callback.html
In C/C++ when a function name is used with no parameters - that is no parenthesis - it is a pointer to a function. So TClassB::Wrapper_To_Call_Display is a pointer to the address in memory where the code for the function is implemented.
Since TClassB::Wrapper_To_Call_Display is a pointer to a void function that takes a single char* it's time is void (*)(char* test) so it matches the type required by DoItB.