Clearscript: Script cannot call public method of a host object whose type is not public.

Created on 23 Jun 2019  路  5Comments  路  Source: microsoft/ClearScript

If the type of a host object is not public, an exception is thrown when script calls a public method of that host object. The object is exposed, so script should be able to access its public members. Below is the code.

using Microsoft.ClearScript.V8;
using System;

namespace ClearScriptDemo
{
    class Person
    {
        public string GetName()
        {
            return "John Doe";
        }
    }

    class Program
    {
        static void Main(string[] args)
        {
            using (var engine = new V8ScriptEngine())
            {
                // expose a host type
                engine.AddHostType("Console", typeof(Console));
                engine.Execute("Console.WriteLine('{0} is an interesting number.', Math.PI)");

                // expose a host object
                engine.AddHostObject("person", new Person());
                engine.Execute("Console.WriteLine(person.GetName())");

                Console.ReadKey();
            }
        }
    }
}

Exception:
An unhandled exception of type 'Microsoft.ClearScript.ScriptEngineException' occurred in ClearScriptV8-32.dll

Additional information: TypeError: person.GetName is not a function

question

All 5 comments

Hi @tu-lehong,

The object is exposed, so script should be able to access its public members.

A script can access members that are _visible_ to it. In this case, the object's type is _not_ visible, so the script can only access visible members of any visible base types, which in this case includes only the public members of System.Object.

To grant your script the ability to access everything visible to Program, you can use ClearScript's AccessContext property:

C# // expose a host object engine.AccessContext = typeof(Program); engine.AddHostObject("person", new Person()); engine.Execute("Console.WriteLine(person.GetName())");

Cheers!

Thank you!

Hi @karimi,

Does ctx implement IGraphicContext explicitly?

Thanks!

Yes @ClearScriptLib
Here's the implementation of that interface:
```c#
class formGraphicContext : IGraphicContext
{
public void LineTo(float x, float y)
{
...
}

    public void MoveTo(float x, float y)
    {
        ...
    }
}

formGraphicContext ctx = new formGraphicContext(e, pen);

```

Hi @karimi,

The formGraphicContext class isn't public, so its non-inherited members are invisible to script code by default. You can use AccessContext as shown above to expand the script engine's access.

Good luck!

Was this page helpful?
0 / 5 - 0 ratings