We are going to be continuing the tutorial, based on the code we write last time.
This time we will be adding two .net functions callable from javascript, one written using the more advanced method, the other written using the simple method.

Simple Method

private static string SuperAwesomeFunction()
    return "Hello From C#";

Pretend that this is your super-awesome function that took weeks to code. It feels all left out not being able to be called from javascript. Lets change that!

We put the following code after we create the object, but before we execute the script.
context.DefineFunction(global, "SuperAwesomeFunction", new Func<string>(SuperAwesomeFunction));

It tells the context that there is a new function, with you providing it the global object we created, the function name and the function delegate.
It uses awesome black magic to convert the JSVal variables to CLR objects and back again.

Change the script(remember that "'Hello' + ' World!'" thing we wrote earlier) to "SuperAwesomeFunction()". If everything was done correctly and I didn't break the code, it should output "Hello From C#".

Advanced Method

The problem with the simple method is that it doesn't know how many arguments were passed in through javascript, you can only use the ones that you want.
private static bool Print(Context context, JSVal[] arguments, out JSVal ret)
    ret = JSVal.Undefined;
    return true;
This is the function for print, the other super awesome function we are going to write.
It shouldn't be to hard to work out what it does, it passes in the context and an argument array, you return the return value;
In this example we return JSVal.Undefined(the javascript equivalent of void) and print out the first argument.
You return true if your function worked, and return false if there is an error, such as an exception.

context.DefineFunction(global, "print", Print, 1, 0);
This is a bit different to the first one, the first three arguments are pretty much identical to the simple method, but it has two new parameters.
The fourth parameter is the number of arguments that you expect, you will get at least this number, possibly more.
The fifth parameter is for flags. When I figure out what they are I will update this. Until then use 0. It seems to work.

Last edited May 17, 2011 at 7:49 PM by Programmdude, version 1


No comments yet.