How can I access .NET Namespaces from script

Jul 25, 2014 at 12:03 PM
How do I have to parameterize the V8Engine to execute an expression like that:

result = engine.Execute("System.Math.PI");
Jul 25, 2014 at 5:59 PM
Edited Aug 7, 2014 at 5:15 PM
There are many examples in the console application demo.

var _JSServer = new V8Engine(); // create the engine
_JSServer.RunMarshallingTests(); // test compatibility
_JSServer.RegisterType(typeof(Object), "Object", true, ScriptMemberSecurity.Locked); // register the "Object" CLR type
// ... ok, now at this point, the CLR type is registered with the engine, BUT, is NOT yet exposed to the SCRIPTING world ...
ObjectHandle hSystem = _JSServer.CreateObject(); // create a new native object to act as the "System" namespace
_JSServer.DynamicGlobalObject.System = hSystem; // create a global "System" property and set it to the new object
// Note 1: Any property added to '_JSServer.DynamicGlobalObject.System' (or even just 'DynamicGlobalObject') will be exposed to JS.
// Note 2: you cannot import entire namespaces for security reasons - only TYPES you need.
hSystem.SetProperty(typeof(Object));  // Set a property on the new native system object to the CLR type "Object" (previously registered)
// Note: If you do not call "RegisterType()" before this, it is fine, and the type will be registered with a default name and security setting.
// You can add types quickly like this:
// ... but, nested types will not be bound, and certain other access may be restricted by default if not custom registered.
// (See also: {Engine}.DefaultMemberBindingSecurity)
/* Here is a contrived example of calling and passing CLR methods/types in JS ... */
> r = Enumerable.Range(1,Int32('10')); // (note: Int32 is a registered CLR type [see above])
> a = System.String.Join$1([Int32], ', ', r); // Note: '$' means it's a generic type, 1 means 1 TYPE argument expected, and the first parameter expects a list of types.
Again, to note, type registration does not add types to V8. It creates fixed bindings where possible to avoid having to use reflection during operations. This is done only once, then cached. You have to explicitly add a type as a js property to expose it. Future attempts to work with those types, or create instances, should be relatively fast.

Hope that helps. Keep in mind, this project was focused primarily on exposing the NATIVE V8 engine to the CLR world. It was never meant to expose .NET to V8; Keep that in mind. The binding features were added much later to support a number of binding requests, and to help make the process a little less convoluted/enigmatic.

Please take a look at the "program.cs" file in the console project. It has the examples in the this post, and much more. If you run the console app, you'll see the examples execute, and can play with it.

Hope that helps. 8)