void xGetFunctionAddress(void* FunctionDefinition, std::string FunctionName)
{
*static_cast<FARPROC*>(FunctionDefinition) = xProcAddress(Module, FunctionName.c_str());
}
In the above code, I'm trying to get rid of that FARPROC* to make it cross-platform. However, if I cast to long long int (*)(), it gives me the error that it cannot statically cast to that. So when I typedef it, it works:
Ex:
//This works:
void xGetFunctionAddress(void* FunctionDefinition, std::string FunctionName)
{
typedef __stdcall long long int (*Ptr)();
*static_cast<Ptr*>(FunctionDefinition) = GetProcAddress(Module, FunctionName.c_str());
}
//This doesn't:
void xGetFunctionAddress(void* FunctionDefinition, std::string FunctionName)
{
*static_cast<long long int(*)()>(FunctionDefinition) = GetProcAddress(Module, FunctionName.c_str());
}
What am I doing wrong in the second example? :S
Your are casting the void pointer to a function pointer and then dereferencing it. This evaluates to an assignment to a function instead of a function pointer. The following should take of the problem
*static_cast<long long int(__stdcall **)()>(FunctionDefinition) = GetProcAddress(Module, FunctionName.c_str());
^^
Notice the additional pointer level next to __stdcall.
It would be useful to see the specific error message, but it looks like you might be missing the __stdcall dcl-specifier in your static_cast. Does it work if you add that?
Edit:
Looking further, it appears this may not be supported. Please see this answer: https://stackoverflow.com/a/1096349/279130 which seems to address the same question.
What is GetProcAddress() defined to return?
If it's a void *, you can't portably cast that to a function pointer. See https://stackoverflow.com/a/1096349/37386
Related
I'm getting a compile error (MS VS 2008) that I just don't understand. After messing with it for many hours, it's all blurry and I feel like there's something very obvious (and very stupid) that I'm missing. Here's the essential code:
typedef int (C::*PFN)(int);
struct MAP_ENTRY
{
int id;
PFN pfn;
};
class C
{
...
int Dispatch(int, int);
MAP_ENTRY *pMap;
...
};
int C::Dispatch(int id, int val)
{
for (MAP_ENTRY *p = pMap; p->id != 0; ++p)
{
if (p->id == id)
return p->pfn(val); // <--- error here
}
return 0;
}
The compiler claims at the arrow that the "term does not evaluate to a function taking 1 argument". Why not? PFN is prototyped as a function taking one argument, and MAP_ENTRY.pfn is a PFN. What am I missing here?
p->pfn is a pointer of pointer-to-member-function type. In order to call a function through such a pointer you need to use either operator ->* or operator .* and supply an object of type C as the left operand. You didn't.
I don't know which object of type C is supposed to be used here - only you know that - but in your example it could be *this. In that case the call might look as follows
(this->*p->pfn)(val)
In order to make it look a bit less convoluted, you can introduce an intermediate variable
PFN pfn = p->pfn;
(this->*pfn)(val);
Try
return (this->*p->pfn)(val);
Just to chime in with my own experience, I've come across an error in g++ caused by this statement:
(this -> *stateHandler)() ;
Where stateHandler is a pointer to a void member function of the class referenced by *this. The problem was caused by the spaces between the arrow operator. The following snippet compiles fine:
(this->*stateHandler)() ;
I'm using g++ (GCC) 4.4.2 20090825 (prerelease). FWIW.
p->pfn is a function pointer. You need to use * to make it function. Change to
(*(p->pfn))(val)
I'm trying to return a pointer to function without the use of typedef, but the compiler (gcc) is emitting a strange error, as if I could not do that kind of setting.
Remarks: With the use of typedef code works.
code:
void catch_and_return(void (*pf)(char*, char*, int&), char *name_one, char* name_two, int& number)(char*, char *, int&)
{
pf(name_one, name_two, number);
return pf;
}
Error:
'catch_and_return' declared as function returning a function
Can you explain to me why the compiler does not let me do this? Thank you!
Declare your function as the following:
void (*catch_and_return(void (*pf)(char*, char*, int&), char *name_one, char* name_two, int& number))(char*, char *, int&)
{
pf(name_one, name_two, number);
return pf;
}
The syntax for functions that returns functions is:
returned-function-return-type (* function-name (parameter-list) ) (function-to-return-parameter-list)
Note: This declarations can be cumbersome to understand at first sight, use typedef whenever is possible
I would like to forward a callback to a function pointer. So I declare a static (int*) m_pointer1, as well as a method void RegisterCallback1( (int*)fct)
in class1.h:
public:
int RegisterCallback1( int (*fct) );
private:
static int (*m_Callback1);
in class1.cpp:
int class1::RegisterCallback1( int (*fct) )
{
m_Callback1= fct;
}
then, I want to forward the callback to the function pointer:
void class1::Callback1()
{
(*m_Callback1)();
}
But I get a compiler error "Expression must have (pointer-to)- function type
I have followed tutorial and read about function pointers and they seem to do it this way without any problems. Any ideas why?
EDIT:
So, I declare (int*)(void)m_Callback1 -Visual Studio requires a void there...-
Then how do I call the registerCallback function with the argument?
class1.RegisterCallBack1( ??? - class2::callback -??? );
static int (*m_Callback1) does not declate a function pointer, just a pointer to int: you forgot about the parameter list. You meant:
static int (*m_Callback1)();
and
int RegisterCallback1( int (*fct)() );
You haven't declared a function pointer, you've declared a normal data pointer. You are missing () at the end of the declaration.
You can try to limit the missing () errors pointed out by Oli and Dave by using a typedef for the callback function's signature: typedef int (*)() CallBack; This would at least have the merit of letting you think once about the precise number of brackets rather than at every point in your code where you use such a function.
I'll try to explain better what I want to do.
I read a file with function signatures, and I want to create a pointer to each function.
For example, a file that looks like this:
something.dll;int f(char* x, int y, SOMESTRUCT z)
something.dll;void g(void)
something.dll;SOMESTRUCT l(longlong w)
now, during runtime I want be able to create pointers to these functions (by loading something.dll and using GetProcAddress to these functions).
Now, GetProcAddress returns FARPROC which points to an arbitrary functions, but how can I use FARPROC to call these functions during runtime?
From what I know, I need to cast FARPROC to the correct signature, but I can't do it during runtime (or at least I don't know how).
Does anyone have any idea how to design do that?
Thanks! :-)
Function types are compile-time in C++, so it won't work, unless you can define all the types you're going to use in advance.
Its a matter of pushing the arguments to the stack (and local vars are like that) and calling the function as void (__cdecl *)(void).
With some other kinds of functions (like fastcall, or thiscall) it can be more problematic.
Update: I actually made an example, and it works on codepad:
(Also works with stdcall functions, because of stack restore after aligned stack alloc)
http://codepad.org/0cf0YFRH
#include <stdio.h>
#ifdef __GNUC__
#define NOINLINE __attribute__((noinline))
#define ALIGN(n) __attribute__((aligned(n)))
#else
#define NOINLINE __declspec(noinline)
#define ALIGN(n) __declspec(align(n))
#endif
//#define __cdecl
// Have to be declared __cdecl when its available,
// because some args may be passed in registers otherwise (optimization!)
void __cdecl test( int a, void* b ) {
printf( "a=%08X b=%08X\n", a, unsigned(b) );
}
// actual pointer type to use for function calls
typedef int (__cdecl *pfunc)( void );
// wrapper type to get around codepad's "ISO C++" ideas and gcc being too smart
union funcwrap {
volatile void* y;
volatile pfunc f;
void (__cdecl *z)(int, void*);
};
// gcc optimization workaround - can't allow it to know the value at compile time
volatile void* tmp = (void*)printf("\n");
volatile funcwrap x;
int r;
// noinline function to force the compiler to allocate stuff
// on stack just before the function call
NOINLINE
void call(void) {
// force the runtime stack pointer calculation
// (compiler can't align a function stack in compile time)
// otherwise, again, it gets optimized too hard
// the number of arguments; can be probably done with alloca()
ALIGN(32) volatile int a[2];
a[0] = 1; a[1] = 2; // set the argument values
tmp = a; // tell compiler to not optimize away the array
r = x.f(); // call the function; returned value is passed in a register
// this function can't use any other local vars, because
// compiler might mess up the order
}
int main( void ) {
// again, weird stuff to confuse compiler, so that it won't discard stuff
x.z = test; tmp=x.y; x.y=tmp;
// call the function via "test" pointer
call();
// print the return value (although it didn't have one)
printf( "r=%i\n", r );
}
Once you have a FARPROC, you can cast the FARPROC into a pointer to the appropriate function type. For example, you could say
int (*fPtr)(char*, int, SOMESTRUCT) = (int (*)(char*, int, SOMESTRUCT))GetProcAddress("f");
Or, if you want to use typedefs to make this easier:
typedef int (*FType)(char *, int, SOMESTRUCT);
FType fPtr = (FType)GetProcAddress("f");
Now that you have the function pointer stored in a function pointer of the appropriate type, you can call f by writing
fPtr("My string!", 137, someStructInstance);
Hope this helps!
The compiler needs to know the exact function signature in order to create the proper setup and teardown for the call. There's no easy way to fake it - every signature you read from the file will need a corresponding compile-time signature to match against.
You might be able to do what you want with intimate knowledge of your compiler and some assembler, but I'd recommend against it.
how do I cast void *something to an object in standard C++?
Specifically I want want to cast void *userdata
to std::map<String, void*>
Is this possible? I am trying:
//void *user_data is a parameter of this function (callback)
std::map <String, void*> user_data_n; //this line is ok
user_data_n = static_cast<std::map<String, void *>>(*user_data); //I get the errors here.
ERRORs:
Spurious '>>' user '>' to terminate a template argument list
Expected '>' before '(' token
'void *' is not a pointer-to-object type
or is there a better way to carry information about the caller object and some other parameters I can pass to void *user_data?
UPDATE:
Ass suggested by #aaa carp I changed >> to > > and the first two errors were solved. The last is strange, Why do I get that kind of message when casting it here and not when putting that object when setting the callback?
std::map<String, void*> user_data_h;
user_data_h["Object"] = this; //this is a MainController object
user_data_h["h"] = h; //h was defined as int *h
createTrackbar("trackbar_H", winName, h, 255, trackbar_handler, &user_data_h);
where createTrackbar is defined as:
int createTrackbar( const string& trackbarname, const string& winname,
int* value, int count, TrackbarCallback onChange, void* userdata);
UPDATE2:
doing this solved my problem but following the same approach, why I still get error when trying to cast objects contained in my map object?
void trackbar_handler(int value, void *user_data){
std::map <String, void*> *user_data_map;
user_data_map = reinterpret_cast<std::map<String, void *> *>(user_data); //WORKED!! ;)
MainController *controller; //the same class type I put using "this" above
controller = reinterpret_cast<MainController *>( user_data_map["Object"]); //ERROR here
int *var = reinterpret_cast<int*> (user_data_map["h"]); //ERROR also here
>> should be > >
and you do not want to dereference void pointer, instead cast void pointer to desired pointer type and then dereference
#casa has already provided you with answer to second problem
When you're casting from a void *, your result will be a pointer too. So the map declaration should be:
std::map <String, void*> *user_data_n;
Second, you should use reinterpret_cast for such (potentially dangerous) casts:
user_data_n = reinterpret_cast<std::map<String, void *> *>(user_data);
Update:
As others suggested, you could simply use a static_cast as well.
Why do I get that kind of message when casting it here and not when putting that object when setting the callback?
Any pointer can be implicitly converted to void *, but when converting it back to a pointer of some specific type, you need an explicit cast.
why I still get error when trying to cast objects contained in my map object?
As already mentioned in the comments, you need to dereference the pointer before using the map object. You might want to define a reference instead to make things easier:
std::map <String, void*> &user_data_map =
*(static_cast<std::map<String, void *> *>(user_data));
An noted, the >> in that line to close your template should be > > (with a space).
Also, if user_data is a void pointer, you cannot dereference it. You could cast the pointer to another pointer type with reinterpret_cast:
std::map <String, void*> *user_data_n_ptr; //note this is a pointer to a map.
user_data_n_ptr = reinterpret_cast<std::map<String, void *> *>(user_data);
This will cast the void pointer to a std::map .
You should be careful with this. void pointers shouldn't typically be thrown around in c++. There may be a better way to do what you want and avoid void * all together.
I suppose this is for serving a C callback? It might be better to have a specialized struct which keeps all those values using the exact types. That way you'd be down to one cast for the whole thing. Something like this:
struct callback_user_data {
my_class* that;
int number;
callback_user_data(my_class* p, int i) : that(p), number(i) {}
};
// the callback
void my_callback(void* user_data)
{
callback_user_data* cbud = static_cast<callback_user_data*>(user_data);
somehow_use(cbud->that, cbud->number);
}
//call the function, passing our user data
callback_user_data cbud(this, 42);
some_function_taking_our_callback(&my_callback, &cbud);
Note that usually I have this seen (and used) this so that not a special type is passed, but only this, which has all the necessary data anyway:
// the callback
void my_callback(void* user_data)
{
my_class* that = static_cast<my_class*>(user_data);
that->f();
std::cout << that->number << '\n';
}
//call the function, passing our user data
some_function_taking_our_callback(&my_callback, this);