How should I use AddHandler in cppwinrt with Handler objects? - windows-runtime

In the C++/WinRT reflection, the API AddHandler is defined as
UIElement::AddHandler(Windows::UI::Xaml::RoutedEvent const& routedEvent, Windows::foundation::IInspectable const& handler, bool handledEventsToo) const
But the handlers seems to only inherit from IUnknown. For example, this is the declaration of KeyEventHandler:
struct KeyEventHandler : Windows::foundation::IUnknown
What is the solution for registering an event handler?

It seems like we need to call box_value(handler) which will convert it into an IInspectable. It is not obvious at all, and you cannot find any samples on MSDN.

To elaborate on iohanson's answer, yes, the delegate needs to be boxed up. WinRT delegates are IUnknown, not IInspectable. AddHandler expects to get an IReference<T> where T is a delegate for a RoutedEvent.
I opened an issue on cppwinrt to see if we can get some more helpful overloads, since cppwinrt we don't do the same magic boxing CX users enjoyed.
https://github.com/microsoft/cppwinrt/issues/776

Related

Clojurescript Add an Event Listener

(defn domready [handler]
(.addEventListener js/window "DOMContentLoaded" handler))
I borrowed this code from here. The problem is I don't totally understand what's going on. JS interop is still a bit of a mystery to me.
.addEventListener
So this is clearly a procedure call, but it's kind of generic. It's like Clojurescript took everything that was inside an object, took it out, and you use it to call that method on "objects". As long as that "object" has the ".addEventListener" property it will call this. Is that what it's doing? Why not use a keyword instead? like (:addEventListener domElement) that seems more logical to me.
js/window
What is this? Is it a namespace or an object? Are they the same thing?
"DOMContentLoaded"
A string, that's familiar.
handler
Also familiar, but does it have a notion of this? Not that I'm really going to miss this.
.addEventListener
So this is clearly a procedure call, but it's kind
of generic. It's like Clojurescript took everything that was inside an
object, took it out, and you use it to call that method on "objects".
As long as that "object" has the ".addEventListener" property it will
call this. Is that what it's doing? Why not use a keyword instead?
like (:addEventListener domElement) that seems more logical to me.
Your mental model about how this works is mostly fine. What it does when it compiles is move the function name to be run as a method on the first argument.
(.method obj ...args) get's transformed to obj.method(...args)
This type of interop comes from the parent language Clojure.
On why do we have an explicit version of calling the function that's not Clojure idiomatic, I think the idea is to have clear separation between what is native Clojure code with Clojure semantics (immutability, friendly to CLJ data structures, etc) and what is interoperating with the host environment (mutable, not friendly to CLJ data structures, etc).
In my opinion it is better to have clear separation between those two given how different the semantics of CLJS and the host platforms are. For me explicitness is better than implicit in this case (it is easy to spot looking at the code what is JS code in CLJS, and what is pure CLJS).
js/window
What is this? Is it a namespace or an object? Are they the same thing?
Both, js/ is accessing the namespace js, which is where CLJS puts the JS namespace (since there is only one and global). window is just grabbing the window variable from the js namespace.
This is no different from how you access variables in other namespaces in CLJS. If you (def a 1) in (ns cljs.test) and then run cljs.test/a that will give you 1. Same form, ns/something-in-that-ns.
"DOMContentLoaded"
A string, that's familiar.
\o/
handler
Also familiar, but does it have a notion of this? Not that I'm really going to miss this.
Not sure what this has to do with handler. It is just a higher order function passed into domready as a parameter, like you would do in JS: function domready (onReady) { window.addEventListener("DOMContentLoaded", onReady) }
I hope this helps, if you want to try it out live and learn some more, maybe visit the Talking with JS on the Diving into ClojureScript tutorial, or maybe check this section of the lt-cljs-tutorial.
I'm just learning clojurescript so I don't really know if it is the correct answer but I've done it in the following way:
(defn handler [] (js/console.log "ready"))
(js/document.addEventListener "DOMContentLoaded" handler)
which is then translated to
cljs.user.handler = (function cljs$user$handler(){
return console.log("ready");
});
document.addEventListener("DOMContentLoaded",cljs.user.handler);
to check how clojurescript translate code I've used KLIMPSE http://app.klipse.tech/
.addEventListener is a method call on the global Javascript object js/window. This method call takes two parameters: "DOMContentLoaded" and handler.
When you are doing interop (either Java or Javascript) you really are calling methods on objects. There are macros behind what is happening here. What is straight after the ( is a verb, which I usually think of as a function call (although it might also be a macro or a special form). When doing interop what comes after the verb is the instance, and after that the parameters.
If it were straight Javascript it would look like this:
function domready(handler){
window.addEventListener("DOMContentLoaded" handler);
}

Fluently choosing which component to inject

I have some components implementing the same interface and I would like to chose which one gets injected to my Repository.
Component.For<IRepository>().ImplementedBy<Repository>().<whatShouldGoHere>()
I thought I had this working with DependsOn but now I saw that DependsOn are for static dependecies such as strings. Is the IHandlerSelector the only way forward? I would rather have the declaration inline with the component registration. Maybe a factory method? Are there any recommendations?
Edit
Example Constructor
public PersitentRepository(Func<ISession,string> sessionFactory)
Digging around I realize that the delegate is an artifact from the TypedFactoryFacility. There seems to have been some change so it now resolves by type only. In older Castle versions the string argument was used to select component by name.
A factory would to the trick.
You need to add the FactorySupportFacility to your container for this to work.
For much more detail, see the Castle Windsor documentation at http://docs.castleproject.org/Default.aspx?Page=Factory-Support-Facility&NS=Windsor&AspxAutoDetectCookieSupport=1.
See also http://www.mail-archive.com/castle-project-users#googlegroups.com/msg04463.html.
DependsOn does work for other things than statics, the problem is that the injected delegate does not resolve the way it used to. I ended up registering my own component for handling this specific delegate
container.Register(Component.for<Func<ISession,string>>().ImplementedBy(sessionName => container.resolve<ISession>(sessionName));
(I typed the above from memory so please excuse any typos)

How to declare Function's bind method for TypeScript

I am trying to use Mootools together with TypeScript. Mootools, and some modern browsers support .bind method, which is polymorphic.
How can I properly declare this feature in a *.d.ts file, to be able to use constructs like [1,2].map(this.foo.bind(this)); ?
I know I can avoid such constructs by using lambdas, but sometimes I do not want to.
Perhaps there is a mootools.d.ts file somewhere which I could download instead of reinventing it myself?
TypeScript's lib.d.ts already defines the bind function's signature in the Function interface as follows:
bind(thisArg: any, ...argArray: any[]): Function;
I don't think there's any better way of doing it until generics get added to the language.
For the time being though, if you want to use bind and the recipient of the resulting function expects a specific signature, you're going to have to cast the function back to that signature:
var bfn : (p: number) => string;
bfn = <(p: number) => string> fn.bind(ctx);
There's a growing list of definition files being tracked here.
As for generating methods pre-bound to their this pointer in TypeScript I've suggested two ways of doing this. 1) a simple base class I defined at the end of this thread. and 2) a more advanced mixin & attribute system here.

hooking via hotpatching... non exported class method in dll

I have been studying this method of API hooking using the mechanisms for hotpatching in windows dlls.
http://www.codeproject.com/KB/winsdk/0xF9EB_Hooking.aspx
I was wondering if anyone would know of a way to extend that to hooking non exported functions such as a C++ constructor for an internal class inside of a DLL. I have already know the address via dis-assembly... the problem I am having is how to set up the right calling conventions so that I can call the original function inside of my hook function.
I'm already to the point to where my hook function gets called... the program crashes because I can't return the results of calling the original function.
Lets assume we are talking about hooking an internal class constructor with a prototype something like this:
public __thiscall <class_name>::<class_name>(<single pointer arg to another object>)
depending on how your module is loaded, you can generally just overwrite the relative or absolute addresses at their respective call sites, else you need to make a trampolining function, for which its easier to use something like MS Detours.
In terms of the correct prototype for __thiscall based class member functions, you need some trickery, as you can't generally use __thiscall outside classes. The fastest and easiest way is to use __fastcall and ignore the second parameter. So your first definition becomes void __fastcall myctor(myobj* pObj).
Define it as a typical __stdcall function except that you'll have this pointer in ecx register. If you need this pointer, then use the __asm keyword to get the value:
void __stdcall HookedConstructor( SomeObject *pObject){
HookedClass *pClass;
__asm mov pClass, ecx;
...
}
Note that you'll have to do this at the beginning of the call. Otherwise, the value of ecx register may be overwritten.

What are callback methods?

I'm a programming noob and didn't quite understand the concept behind callback methods. Tried reading about it in wiki and it went over my head. Can somebody please explain this in simple terms?
The callback is something that you pass to a function, which tells it what it should call at some point in its operation. The code in the function decides when to call the function (and what arguments to pass). Typically, the way you do this is to pass the function itself as the 'callback', in languages where functions are objects. In other languages, you might have to pass some kind of special thing called a "function pointer" (or similar); or you might have to pass the name of the function (which then gets looked up at runtime).
A trivial example, in Python:
void call_something_three_times(what_to_call, what_to_pass_it):
for i in xrange(3): what_to_call(what_to_pass_it)
# Write "Hi mom" three times, using a callback.
call_something_three_times(sys.stdout.write, "Hi mom\n")
This example let us separate the task of repeating a function call, from the task of actually calling the function. That's not very useful, but it demonstrates the concept.
In the real world, callbacks are used a lot for things like threading libraries, where you call some thread-creation function with a callback that describes the work that the thread will do. The thread-creation function does the necessary work to set up a thread, and then arranges for the callback function to be called by the new thread.
Wiki says:
In computer programming, a callback is
a reference to executable code, or a
piece of executable code, that is
passed as an argument to other code.
This allows a lower-level software
layer to call a subroutine (or
function) defined in a higher-level
layer.
In common terms it is the mechanism to notify a piece of code i.e. a method, which piece of code to execute, i.e. another method, when it is needed.
Callback is related to the fact that the client of the calling function specifies a function that belongs to the client code's responsibility to the calling function to execute and this is passed as an argument.
An example is in GUIs. You pass as argument the function to be called once an event occurs (e.g. button pressed) and once the event
occurs this function is called.
This function is usually implemented by the object that originally registered for the event
Callback function is a function that is called through a function pointer. If you pass the pointer (address) of a function as an argument to another, when that pointer is used to call the function it points to it is said that a call back is made.
Why Should You Use Callback Functions?
A callback can be used for notifications. For instance, you need to set a timer in your application. Each time the timer expires, your application must be notified. But, the implementer of the time'rs mechanism doesn't know anything about your application. It only wants a pointer to a function with a given prototype, and in using that pointer it makes a callback, notifying your application about the event that has occurred. Indeed, the SetTimer() WinAPI uses a callback function to notify that the timer has expired (and, in case there is no callback function provided, it posts a message to the application's queue).
In general you supply a function as a parameter which gets called when something occurs.
In C code you will pass something that looks like this:
int (callback *)(void *, long );
meaning a function that takes two parameters, void * and long and returns an int.
With object-orientated languages the syntax is sometimes simpler. For example you might be able to construct a callback mechanism that allows the user to pass in an object that looks like a function or has an abstract method (thus wrapping a function) and context data too.
Modern languages use the term "delegate" to refer to a function "pattern". These can be used as callbacks. Some languages also use the term lambda which is essentially a function with no name, often created "on the fly" in a block of code and passed as a callback.
C++11 has introduced these into its standard.
The advantage of using a callback is that you can separate out, i.e. reduce / decouple an API from what is calling it, and to some extent vice versa, i.e. although in one place you know you are calling into the API, at the point of the "handler" it does not need to know from where it was called.
For example, you can have an API that generates objects and then "calls-back" as they get generated.
Call back means that you pass the code as a parameter. For example, imagine a button, that much show a dialog when pressed:
Button testBtn;
testBtn.setOnClickListener(new OnClickListener() {
#Override
public void onCLick() {
JOptionPane.showDialog(testBtn, "Test button pressed");
}
}
Here we tell the button what to execute, when it will be click. So, the framework will execute the passed code, when it detecs the click. Inside the framework there are some code like:
void processEvent(Event e) {
if (e.type == Event.CLICK) {
e.getComponent().getOnClickListener().onClick();
}
}
So, some basic code calls back the listener when the appropriate event happens.
PS: Pseudocode here, just do describe the idea.
A callback method is a method that gets called when an event occurs
In simple word, actually, a Callback is a reference to a function or method, which you can pass as a parameter to another function for calling it back later.
From the above figure, B_reference() is the callback method.
Source code sample:
>>> def A(A_msg,B_reference):
... # After printing message, method B is called.
... print(A_msg)
... B_reference()
...
>>> def B():
... print("Message from B")
...
>>>
>>> A("Message from A",B)
Message from A
Message from B
>>>
If you still don't understand what it is, you can check this video: