How can I pass a pointer to function to another function? I have a function like this:
std::string PRINT_STATE_NAME(pPrintState func);
where pPrintState is a typedef like this:
typedef void (*pPrintState)(std::string* buffer);
So I JITed pPrintState and have its llvm::FunctionType available.
Next I want to call PRINT_STATE_NAME() as defined above from llvm C++ API. Unfortunately I can't figure out what parameter to pass to the call instruction. Atm I made an llvm::GlobalVariable with inner type of converted pPrintState. But what should I pass as initializer? Or am I completely on the wrong track here? Any help is appreciated! Thanks!
You need to obtain the address of pPrintState (the JIT'ed one, via getPointerToFunction() or getPointerToNamedFunction()) cast this address (as integer) to pPrintState and pass as an argument.
Related
My application needs parts of a C++ code to be called from a C program.
The problem arises when i have to obtain the address of a public function.
I do not know how to get the address of a public function from a class.
I specifically need the address so that i can pass the address as a function pointer.
Any other solutions to circumvent the solution are also welcome.
I have tried static casting but it has not worked.
static_cast<izot_events*>(thisizot_events)->myIzotWink()
This calls the function but i am interested in the address.
I have tried using
static_cast<izot_events*>(thisizot_events)->myIzotWink
But this returns an error.
Here is also some code for reference.
void* C_Create() { return new izot_events(); }
thisizot_events = C_Create();
static_cast<izot_events*>(thisizot_events)->myIzotWink // This does not work i.e I cant get the value.
static_cast<izot_events*>(thisizot_events)->myIzotWink() // While this gets called
Make the function static, then you can do &MyClass::my_function. You should not do any casting; instead make your static function have the right declaration to match the function pointer's type.
I'm having a problem with function pointers and nothing I found on the net helped me to solve this problem.
I have a function from a C API which take a pointer of a void function :
extern int APIFunction(int, void (*func)(int));
I have a class with the function I would like to put when I call the API function.
class MyClass
{
public:
void myFunction(int status, otherAPi arguments...);
};
Then, I created a pointer to my member function and created a new instance of my class
typedef void (MyClass::*MyClassFunctionPointer)(int stat, otherAPi arguments...);
MyClassFunctionPointer fctPointer= &MyClass::myFunction;
LicenseSecurity instance;
I get an error when I try to call my APi function with the function pointer I created:
int stat = APIFunction(5, fctPointer ); // -> error 1
int stat = APIFunction(5, instance.*fctPointer ); // -> error 2
I got errors respectively in the first and second case:
E2034 Impossible to convert 'void (MyClass::*)(int, otherAPITypes...)' into 'void (*) (int, otherAPITypes...)'
E2342 Bad type correspondence in the parameter 'func' ('void (*)(int, otherAPITypes...)' desired, 'void(int, otherAPITypes...)' obtained)
I don't have access to the API function so I can't modify it. To summary the problem: how How to get a "simple" C function pointer to put in argument of a function from a member function of my class?
Thanks
Unfortunately, you can't. Sorry.
Ideally, your API would accept something like std::function that would allow you to wrap free functions or member functions. But if you can't modify the API, then you have no choice but to provide a free function.
You can't get a "simple" function pointer to a non-static member function because the function requires a this pointer when called. If you were to create a function pointer like that then when the function was called there would be no this pointer for it to reference.
With an ancient C API like that, you unfortunately don't have any way to do this.
What you have to do is make a static or non-member function to take the callback, and then figure out which instance of the object to call the member on. Some C APIs allow a user data to be passed to the callback, and in that case you use that to store the this pointer in question. If that's not an option you can use a global or singleton object and only allow a single such callback to be registered.
You can declare the callback as either a standalone function or as a static method of the class. The tricky part is accessing a class instance pointer inside the callback.
Ideally, a well-designed API allows you to specify a user-defined value to callbacks. That allows you to easily pass in a class instance and access it directly inside the callback. But it sounds like you are not working with such an API, so you need to use a workaround.
If you have only 1 class instance being used with the API at a time, you can store the instance pointer into a global variable, and have the callback use the global variable to access the instance.
But if you have multiple class instances being used at the same time, you are looking for a thunking solution, similar to the VCL's MakeObjectInstance() function, which allows TWndMethod-signatured class methods to be used as Win32 window procedure callbacks. Essentially, a block of executable memory is dynamically allocated, stub assembler code is written into the block, and the instance pointer and class method pointer are stored in the block as well. The block is then passed to the API as if it were a function pointer. When the API calls the "function", the stub code gets executed, which has to manipulate the call stack and CPU registers to call the stored class method pointer passing the stored instance pointer as its hidden this parameter, while preserving the semantics of other parameters, the call stack, function result, etc.
Nothing in C++ really accomplishes that kind of thunking natively. It is not difficult to implement manually, but it is not trivial either (have a look at the source code for MakeObjectInstance() in the VCL's Classes.pas source file). The hardest part is coming up with the necessary stub code that matches the semantics of your particular class method's signature.
I am new to Objective-C and I need to overcome the following issue.
I am trying to develop a front-end for a C library and I need to somehow get the address of an Objective-C member function and pass it to the library.
For instance: here's what I would do in C++
class MyClass
{
public:
void my function();
void some_other_function()
{ connect_signal(my_function); }
};
Here, I just pass the address of my_function() to connect_signal.
Is that possible in Objective-C? Any other ideas?
My second choice would be to simply write a C function out of the class that would call the Objective-C function.
Thanks in advance
There’s a methodForSelector: method that returns an IMP, a pointer to the implementation of a method for given selector (related question). Is that what you’re after?
And as a more general remark, using a pointer to a method implementation is usually too much magic. Is there a higher-level, more “ordinary” solution to your use case? (I can’t really imagine the details from what you wrote in the question.)
For the record, you can't connect a signal to a nonstatic C++ function. At least not in the *nix meaning of signals. Those need a this pointer for invokation.
Now, about Objective C. Depends on what do you want to do - pass a pointer to an Objective C method to a plain-C API, or implement a signal-like callback mechanism of your own. Other answers concentrate on the former; let's talk the latter.
The natural thing to do is passing around a combination of a selector and an object pointer. Selectors have datatype SEL and are retrieved using the #selector() construct. A selector is a piece of data (really an integer) that uniquely identifies a method within a class hierarchy.
Let's imagine you have a connect_signal function somewhere that wants a callback:
-(void)connect_signal:(SEL)callbackSelector forObject:(NSObject*)callbackObject;
You call it like this (from within the callback object):
[xx connect_signal:#selector(MyMethod:) forObject:self];
Within the function, you save the selector and the object pointer. When you need to invoke the callback, you would issue the following call:
[SavedCallbackObject performSelector:(SavedCallbackSelector) withObject: nil];
The second parameter is for passing parameters to the callback; if you need more than one, see NSInvoke.
My answer is assuming Cocoa. NSObject, e. g. is a Cocoa class. It's a safe bet for ObjC questions these days, considering.
Or you can use good old function pointers. They're still around.
An Objective-C method implementation (IMP) is a C function that takes at least two arguments; the target of the method call (self) and the selector to be invoked (_cmd).
Thus, passing an IMP to your C API won't work.
Your best bet is to pass a C function. Assuming your C API is sensible and has an "arbitrary user context pointer thingy", something like:
void myfunc(void *context) {
[(MyClass *)context callback];
}
I'm currently working with Qt and a graphics engine and during the init of the QGLWidget instance I need to pass a few function pointers to my engine.
The function looking for callbacks is:
virtual void Buffer::CreateCustom( byte* getsize, byte* makecurrent)
Qt provides a makeCurrent function however it is neither byte* nor static.
I could write a tiny wrapper function like so:
void _stdcall MakeCurrent(void)
{
QGLContext::makeCurrent();
}
But its only meant to be called from within an instance of GLWidget. I tried to create a class member wrapper function like so:
void _stdcall LEWidget::leMakeCurrent(void)
{
makeCurrent();
}
But you can only provide function pointers on static member functions. If I do that I get the following error:
error C2352: 'QGLWidget::makeCurrent' : illegal call of non-static member function. A nonstatic member reference must be relative to a specific object.
See this question, I think it is pretty much what you want to do:
How do I implement a callback in C++?
You can't. That's what std::function exists for. You need to either change your interface to use std::function, get lucky and find some kind of void* context argument, or give up.
This is because it is impossible to tell(from the compiler's POV) which this pointer should be pass into that function when that callback is called. If you really really want to pass in a pointer, you'll have to use assembly.
I would like to make an alias in C++ to singleton calling
so instead of calling MYCLASS::GetInstance()->someFunction(); each time, I could call just someFunctionAlias(); in my code.
Use a static function.
namespace ... {
void someFunction() {
MYCLASS::GetInstance()->someFunction();
}
};
Edit: Sorry lads, I wrote static someFunction and meant void someFunction.
typedefs are used for type aliases but can't be used as call alias.
functions (such as suggested as by DeadMG) can be used as a call "alias".
PS. As this is C++ you have lots of options, function pointers, std::tr1::function<> operator overloading and the preprocessor. But in this case it certainly looks like a simple function would be the simplest and best solution.
Look up function pointers.
You can create a function pointer, and assign it to your long function. You can then call this function pointer just like a regular function, wherever your variable is defined.
Function pointers can be confusing, but are used a lot in API callbacks (i.e. you pass a function as an argument to the API, and the API will call that function when something happens (think WndProc)).
Good luck.
you can do this
#define someFunctionAlias MYCLASS::GetInstance()->someFunction()