I know C on UNIX has signal() to call some function after some actions. I need it on Windows. I have found, what it exists from here. But I don't understand how to use it correctly.
I tried it like in UNIX:
signal(SIGINT, signalFunction); //attach function to signal
void CRegBackupWiz::signalFunction(int sigNum) //function
{
m_Parent->SetWizard (swContinueFix);
}
I can't find, what is wrong with my code. Thanks for advices, I appreciate that.
Okay so you need to look at how to use function pointers, and in particular how to use pointers to member functions : http://www.parashift.com/c++-faq/pointers-to-members.html.
In general if you are using a pointer to a function as a callback mechanism you should use a top level free function (non-member) as a wrapper. See here:
http://www.parashift.com/c++-faq/memfnptr-vs-fnptr.html
That code doesn't actually work under Unix either.
Pointers to members are different from ordinary pointers - you need to use either a free function or a static member function.
Related
I'm trying to call a member function of an external library which takes a function pointer as a parameter:
Timer::every(unsigned long period, void (*callback)(void));
But unfortunately the parameter I want to pass is a member function:
void MyClass::the_method_i_want_to_pass(void);
Since I'm programming for the ATMega under Arduino (AVR) there is just limited support of c++11. My first approach raises a type error:
void MyClass::the_method_i_want_to_pass() {...}
MyClass::MyClass() {
// constructor
Timer *timer = new Timer();
timer->every(500, [this](){this->the_method_i_want_to_pass();})
}
Compiler Output:
warning: warning: lambda expressions only available with -std=c++11 or -std=gnu++11 [enabled by default]
error: no matching function for call to ‘Timer::every(int, MyClass::MyClass()::__lambda0)’
Are there other/better solutions?
Concerning my current approach: (How) is it possible to pass a reference to a lambda when a function pointer is required?
How can I find out if Arduino/AVR supports these lambdas (see "warning")?
Your basic problem is your Timer library is poorky written: it should take void(*)(void*), void* at the least.
Without a pvoid or equivalent, you cannot pass any state other than the address in execution code to run the procedure at. As a method also rewuires a this pointer, you are out of luck.
Now, if your instance of MyClass is a singleton, you can get this from somewhere else.
Failing that, you need to make your own global state that lets you map from a particular callback to some state. If you have a limited number of MyClass and other consumers of Timer, you can have a few fixed functiins, and have them store their extra state globally.
This is all a hack. What follows is worse.
Write a dynamic library with some global state, and a void() interface. When you add a callback, duplicate that dynamic library, modify its global state at runtime, write it out as a differently named library, load it, and pass the pure callback function to your Timer class.
Or do the equvalent without a library by manually writing machine code and marking pages as execuable.
These are all poor solutions. Which leads me to a good one: find a better Timer. If they screwed up something that simple, the rest of the library is probably bad as well.
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 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()
I have a DLL which has a function which accepts a function pointer converts it to a boost::function. This is then stored and then called from inside the DLL.
I want to add a function to the DLL to handle member functions in a similar way. I know I need to use boost::bind to wrap the member function pointer and the object together. I want to do the binding on the DLL side though so the EXE does not require boost libraries to be included.
How would you write this function? One which accepts a member function pointer and an object as arguments and binds them together.
Thanks!
you're warned by #Kylotan, so you can try something like this:
__declspec(dllexport) void store_mem_fn(void(Your_class::*mem_fn)(void), Your_class& instance)
{
std::vector<boost::function<void(void)> > container;
container.push_back(boost::bind(mem_fn, instance));
}
It might be a bad idea to try passing member function pointers into DLLs because they can vary in size depending on certain circumstances. (Some details here.) Maybe if you always know that you will be building both halves of the application with the same compiler you will be ok.
As for the function, I expect it would look something like this (completely untested and uncompiled code):
typedef void(ObjectType::*OTMemberFn)();
boost::function<void (ObjectType o)> bind_mem_fn(ObjectType o, OTMemberFn mf)
{
return boost::bind(mf, o);
}
Isn't Boost open source? If so, peek into the boost code, learn how it's done, and re-implement it yourself, without the dependency.
What is mean by delegates in c++, does sort function in c/c++ which takes a compare function/functor as last parameter is a form of delegate?
"delegate" is not really a part of the C++ terminology. In C# it's something like a glorified function pointer which can store the address of an object as well to invoke member functions. You can certainly write something like this in C++ as a small library feature. Or even more generic: Combine boost::bind<> with boost::function<>.
In C++ we use the term "function object". A function object is anything (including function pointers) that is "callable" via the function call operator().
std::sort takes a "predicate" which is a special function object that doesn't modify its arguments and returns a boolean value.
Callback functions in C++ can be (loosely) referred as a form of delegates ( though delegate term is not used for this). The callback functions use Pointers to Functions to pass them as parameters to other functions.
But delegates in C# is more advanced compared to callback functions in C++.
To delegate work means to share the work load with others. In real life, if you were to delegate your task, ie if you are a manager, you would be sharing your work expecting others to complete a task without you having to know how.
The concept is the same in C++ and any other languages having the capability of delegates. In C you could see this as a delegate:
int calculate(int (*func)(int c), int a, int b)
Because you are expected to send a pointer, to another function which will compute some work for you. I recently wrote a blog post on function pointers in Python and C, check it out, you might find it helpfull. This might not be the "traditional" way to delegate work in C or C++, but then again, the termonoligy says i am a bit right.
Delegation is mostly used as a way to pass functions to functionality embedded in a class (pimpl, aggregation, private inheritance). They are mainly (inlined) functions of one line, calling functions of member-classes. As far as I know, it has nothing to do with C#'s delegates.
In this sense, a function-pointer as used in qsort is not a delegate, but a callback in which framework modules can be extended by user-software as in the Hollywood principle.
Delegate: An object that acts like a multi-function pointer with a subscription system. It really simplifies the use of static or 'object' member function pointers for callback notifications and event handling.
This link explains Delegates in a lucid manner or you may also refer to the MSDN link.