First I should tell you that ive little knowledge of Objective C or C#.So when one of my collegues asked me whether there is anything like delegates in Objective C,I wondered if such a concept existed in Objective-C.I guess the delegates we use in iphone programing are not the same.C# delegates are function pointers right? Such a facility would be nice to have while working with multiple views.Where can i find info??
Delegates in Objective-C are merely a concept, not some kind of implementation artifact (like in C#). A delegate in Objective-C (better: Cocoa) is basically an object, which is notified by whoever uses it as its "delegate" of certain events occuring. Delegates may also be asked to perform certain tasks on behalf of the host object. The interface a delegate is required to implement is often formalized by a protocol.
#protocol ActionDelegate
- (void) actionDidStart: (id) aSender;
- (void) actionDidEnd: (id) aSender;
#end
#interface Action: NSObject {
id<ActionDelegate> delegate;
}
#property (nonatomic,assign) id<ActionDelegate> delegate;
#end
Delegates in C#, on the other hand, are an implementation artifact. There is a dedicated delegate keyword to declare delegate types and to create actual delegate instances.
class Action {
delegate void ActionDidStartDelegate(Action sender);
delegate void ActionDidEndDelegate(Action sender);
...
}
(my C# is a bit rusty, so the syntax may be off here, sorry; and in real life, one would probably use events in situations like the above rather than raw delegates). Basically, a C# delegate is akin to a Python method object.
You might be able to use the new code block feature of Objective-C to emulate delegates. Not having used this feature (yet), I cannot comment on this. Another way to get something like that would be to use plain function pointers.
typedef void (*callback_function)();
- (void) doSomethingWithCallback: (callback_function) func {
...
func();
}
And of course, you can always use the method often employed by Cocoa itself: use an object and an associated method selector:
- (void) doSomethingWhenDonePerform: (SEL)aSelector onObject: (id) aReceiver {
...
[aReceiver perform: aSelector];
}
C# delegates are something like NSInvocations in Objective-C:
each knows the object that will be the target of the call
each knows the method that will be called
however, an NSInvocation goes further:
it knows the arguments to pass to the method
it can store the return value
You probably wouldn't use NSInvocation to implement a pattern like C# delegates (which are a form of Proxy pattern). Personally I'd choose to use an object that forwards messages it receives to the target object, using the standard message-forwarding features of the runtime.
Related
Especially in the case of events I was wondering if there's a good reason to choose one over the other?
C# example:
Class A
public event System.Action<someparam> someevent;
Class B
void eventcalledmethod(someparam param){
//do something with param
}
Vs.
Class A
public event System.Action();
public static someparam Getter{get;}
Class B
void eventcalledmethod (){
//do something with A.Getter
}
The second example is used in the Microsoft Windows C++ API for the handling of window events.
Answering as I'd argue that this is not a matter of style, as the first method provides different functionality to the second (ignoring doing silly things that you wouldn't normally do anywhere else in your code base).
The first method has the benefit of being able to pass information about a specific instance of A (or any other information required for the event). This is idiomatic and follows normal OOP practices regarding polymorphism and encapsulation. In terms of patterns, it allows for dependency injection amongst other things.
The second method ties the event handling to a static property of A, meaning each instance of A cannot have it's own values for that. It's also not idiomatic, in that most programmers expect the event to contain all information needed for handling the event - tying the handling to a static property adds unnecessary coupling.
I know this might seem like a style argument, but I'd really argue the first is simply more flexible and as such should be preferred where possible.
I have a .NET library, that needs to be exposed for COM interop, including some asynchronous operations. As such, I need to implement events. Implementing events from C# seems easy as:
[ComVisible(true)]
[Guid("...")]
[ClassInterface(ClassInterfaceType.None)]
[ComSourceInterfaces(typeof(IClass1Event))]
public class Class1: IClass1
{
public delegate Int32 IntIntFunc(Int32 arg);
public event IntIntFunc Event;
public Int32 RaiseEvent(Int32 param)
{...}
}
[ComVisible(true)]
[Guid("...")]
public interface IClass1
{
Int32 RaiseEvent(Int32 param);
}
[ComVisible(true)]
[Guid("...")]
public interface IClass1Event
{
Int32 Event(Int32 param);
}
But I have trouble implementing a C++ event sink.
Various examples I've come across range from plain IConnectionPoint::Advise to mere "use VB", but I come across every kind of problem trying to implement them (and no, I can not use VB) - either ATL refuses to implement AddRef for me, or I can not grasp VTables with my mind (I am very basically versed in C frameworks, unfortunately).
I have no information on what framework is preferable, only that client is C++.
So my question is: what'd be the leanest way to expose .NET events to C++, and consequently, what'd be the simplest way to implement a test sink?
P.S.: Do I really need an events interface to be IDispatch?
C++ vtables are very easy, if you're familiar with COM. Microsoft pretty much defined them to be identical. That's to say, the MSVC++ vtable for class IUnknown is binary the same as the COM function table of interface IUnknown.
Now, you seem to stumble on IConnectionPoint::Advise. That's understandable. It looks like an interface that you must implement, but it isn't. It's an interface implemented by the event source. You use it to tell the source what sink to use.
To see what happens, pass a dummy IUnknown object to IConnectionPoint::Advise and put a breakpoint on your IUnknown::QueryInterface. You'll see the event source query for IClass1Event, by GUID of course. Now, when you implement that, you can return it from IUnknown::QueryInterface.
You don't need to implement an IDispatch interface. .Net can do without; it's the old Visual Basic 6 which needs it. That's because VB6 is weakly typed and needs late binding.
More reading material.
( complete duplicate of http://old.nabble.com/C%2B%2B-pointer-to-method-as-parameter-to-C--td17645155.html , but couldn't make the proposed macro work)
I've got the following C++ function (simplified) :
InputPort addInputPort(void(*callback)(InputPort));
Problem : the signature of the generated C# function is :
public InputPort addInputPort(SWIGTYPE_p_f__InputPort____void callback)
SWIGTYPE_p_f__InputPort____void is not a delegate (and has no public constructor anyway), so I can't use addInputPort.
How do I tell SWIG to use a delegate instead ? If the solution involves %typemap, please be extra patient with me...
The solution involves a %typemap. The effect you are seeing is the default useless mapping for unknown types. In your case, the unknown type is the function type void *(InputPort).
In fact, all of SWIG's translation is based on %typemaps which have already been written and live in standard SWIG libraries. You can investigate the initial %typemaps for C# in this Subversion location.
In particular, look for SWIGStringHelper in csharphead.swg. That code maps a delegate to a C callback. The trick is to add a helper callback implementation in the SWIG module.
Are callback functions equivelent to events in C#(.NET).
What I understand about callback function is, it is a function that is called by a reference to that Function.
Example Code will be:
void cbfunc()
{
printf("called");
}
int main ()
{
void (*callback)(void);
callback=(void *)cbfunc;
callback();
return 0;
}
Now What I dont understand is How is this use full with respect to notifying from the DLL to client.
Suppose I want to do /perform some method1() when I recieve Data on my DLL method2().
Any comparasion with Events in .NET will be helpfull in a great way.
Callbacks and interface classes are great ways to manage your code boundaries. They help create formal boundaries and/or layers in your code instead of lumping everything together. This becomes necessary when working on large software solutions.
Below is an example of how to use callbacks and interface classes. In the library/dll code the only thing that should be exposed to the main executable is the myddl_interface class and the function getMyDllInterface(). Using an interface class like this completely hides the implementation detail from the main executable. The interface class also allows the main executable to register a function with it that will be executed later (i.e. callback).
// Begin library/dll Public Interface used by an executable
class mydll_interface {
public:
typedef void (*callback_func_t)();
public:
virtual void do_something() = 0;
virtual void registerFunction( callback_func_t ) = 0;
};
static mydll_interface* getMyDllInterface();
// End library/dll Public Interface used by an executable
// Begin library/dll Private implementation
class mydll_implementation : public mydll_interface {
public:
void do_something() {
printf("Hello World\n");
_callback_func();
}
void registerFunction( callback_func_t c) {
_callback_func = c;
}
private:
callback_func_t _callback_func;
};
static mydll_interface* getMyDllInterface() {
return new mydll_implementation();
};
// End library/dll Private implementation
// Begin main executable code
void myMainAppFunc() {
printf("hello World Again\n");
}
int main() {
mydll_interface* iface = getMyDllInterface();
iface->registerFunction(&myMainAppFunc);
iface->do_something();
};
// End main executable code
You pass the pointer to a 3rd-party routine (doesn't have to be a DLL) and it is "called back" when notificastion is required, by the cloned pointer.
It is similar to .net events in that the latter are also a type of a callback.
BTW, DLLs are less popular in C++ than they are in .NET. This is due to impossibility of sharing static variables (and therefore, singletons), the problem also known as lack of dynamic linking (in UNIX systems, this is solved with Shared Objects, which are quite a different concept of dynamically loaded library). Static libraries offer a better code reuse strategy.
Callback functions fulfill a similar purpose to delegates in C#.
For example, the Win32 API provides a timing service, that is accessed by calling SetTimer. SetTimer is exported by a system DLL, but the mechanism is exactly the same as if used in a user dll. In your code you would access the timer by doing something like this:
void
CALLBACK
MyTimerCallback(HWND hwnd, UINT uMsg, UINT_PTR idEvent, DWORD dwTime)
{
// do something
}
...
TIMERPROC fn = &MyTimerCallback;
int delay = 500;
SetTimer(NULL,0,delay,fn);
Calling SetTimer, and passing in the callback function, allows the operating system to call back into the function each time the timer ticks. Of course, there is no multicast capability here, and, especially in the case of SetTimer, the callback function must be a C function or static class method. There is no class or object instance associated with the function.
A similar pattern could be done in .NET - Im sure .NET has its own Timer paradigm but for a moment we could pretend that it implements a SetTimer function that takes a TimerDelegate.
In user code, in an object you would then define the MyTimerProc as a function with a signature that matches the delegate. And invoke it like this
TimerDelegate d = new TimerDelegate(myObject.MyTimerProc);
SetTimer(0,0,delay,d);
Or, if "timers" was an event that matched the TimerDelegate, then the equivalent C# code would look something like:
timers += new TimerDelegate(myObject.MyTimerProc);
Note: My C# is very rusty so don't take those code samples as any kind of example of either best practices, or even working code :P
When defining your own callback functions it is good practice to always define callback functions to take a void* "context" parameter, as that allows C++ programmers to store their "this" pointer and retrieve it.
// the first parameter to the callback fn is a void* user supplied context parameter
typedef void (CALLBACK* MyCallbackFn)(void* context, int etc);
// and, the dll export function always takes a function pointer, context parameter pair.
DLL_EXPORT void SomeExportedFn(MyCallbackFn, void* context);
A notable example is qSort(), it needs a callback function to compare 2 items.
Callback function can leave some behavior decided at runtime.
If some behavior should be decided by client side dynamically at runtime, then I will ask clients to supply callback functions.
I understand the benefits of events using delegate types with signature delegate void delegate_name(object sender, EventArgs e)
a) But besides the fact that it may save us some typing, are there any other reasons why we should use already defined delegate types EventHandler/EventHandler<T> instead of declaring our own delegate types with signature delegate void delegate_name(object sender, EventArgs e)?
b) Two other reason I can think of for using the predefined delegate types EventArgs/EventArgs<T> are:
people consuming particular event ( say event EventHandler my_event ) will immediately know how to use that event?
perhaps some popular third party methods accept as parameters EventHandler/ EventHandler<T> delegate types, and thus if there’s any chance that our code may use those third party methods, we should use predefined delegates EventHandler/Eventhandler<T>?
thank you
To me, the question is a little strange. What would be the benefit of doing this otherwise (defining delegate types that exactly match EventHandler<TEventArgs> for some TEventArgs)?
That said, there is at least one benefit I can think of to doing it the "normal" way: certain APIs already expect to deal with EventHandler<TEventArgs> delegates; for example, Rx Extensions includes a method that looks like this:
Observable.FromEvent<TEventArgs>(
Action<EventHandler<TEventArgs>> addHandler,
Action<EventHandler<TEventArgs>> removeHandler
);
If you defined your own delegate, using methods like this -- which expect EventHandler<TEventArgs> delegates -- would become more complicated than necessary for no added benefit (that I can see, anyway).
You forgot an important one:
the lunatic that will maintain your code some day will find out where you live and hurt you.
You've answered your own question:
Syntactical Sugar (less to write) to maintain the convention
Interoperability (using the EventHandler type let's you easily integrate events from other libraries
In short; there's no good reason not to use it unless you're forced to (which typically is the result of people not being aware of it, or not understanding it).
From Pro C# 2008 and the .NET 3.5 Platform:
When the compiler processes the event keyword, you are automatically provided
with registration and unregistration methods* as well as any necessary member
variables** for your delegate types. ...To be sure, the event keyword is
little more than syntactic sugar in that it simply saves you some typing time.
* This includes overloading the handy += and -= operators.
** ...which are already marked private so they can't end-run.
When you use the generic EventHandler delegate, you don't even have to write out your custom delegate type at all.
I'm going to rock the boat here and propose something entirely heretical. I used to be firmly in the EventArgs camp because I clung to the "MS recommends this and it's always been done this way" mentality, but over time I came to hate EventArgs. Why?
It promotes a .NET-1.0ish style of coding which relies upon weak-typing/type casting and makes me feel unclean.
It forces your class which implements the event to pollute the heap with new EventArg instances every time it fires, which also makes me uneasy. Why not have my events give subscribers exactly what they need instead of wrapping it up in an extra class that does nothing for me.
The signatures of your callback methods which subscribe to the event look like garbage and have very little semantic detail - e.g. object sender - WHAT is sender?!?!
What I do now is declare my own event handler delegates, which I store neatly in their own "Delegates" folder in my solution as well as their own namespace. So my delegate may reside in its own file like this:
namespace MyAPI.Data.Delegates
{
public delegate void DataEventHandler<TData>(DataFeed<TData> sender, TData data);
}
The event declaration now looks like this:
public event DataEventHandler<TData> DataReady = delegate { };
Benefits to this approach:
Method signatures have more semantic detail. You know WHO is sending WHAT.
Strong-typing is preserved. No more casting object sender to what you think it should be.
You don't have to new() up objects and pollute the heap, which can be problematic if your event fires frequently. Just pass your subscribers exactly what they need, whether it be an object reference or a value type.
By using the ___EventHandler naming convention for your delegates, you are still promoting a uniform style for your code which makes it easy for users of your API to know what your intent is.
The only "drawback" is that it makes it hard for users of your code to wire up your event to existing methods which have the object sender, EventArgs e signature. However, this point is moot because if your event delivers any extra data (e.g. you created your own EventArgs subclass) then they'll have to change the method signature anyway (or cast to your subclass type). Either way, that's still nasty.
That's why I like my way.