method 'is inaccessible due to its protection level'

Mar 6, 2014 at 9:55 AM
Hi,

In the following short test when the script tries to access the method I get a ScriptEngineException:
"'ClearScriptAccessTest.TestClass.TestMethod()' is inaccessible due to its protection level"
However, accessing the property succeeds.
    class TestClass
    {
        public int TestProperty { get; set; }

        public void TestMethod()
        {
        }
    }

    class Program
    {
        static void Main(string[] args)
        {
            using (var engine = new V8ScriptEngine())
            {
                try
                {
                    TestClass testClass = new TestClass();
                    engine.AddHostObject("testClass", testClass);
                    engine.Execute(
                        @"
                    testClass.TestProperty = 17;
                    testClass.TestMethod();
"
                        );

                }
                catch (Exception ex)
                {
                    Console.WriteLine("Error: '{0}'", ex.Message);
                }
            }

        }
    }
The obvious workaround is to change
class TestClass
to
public class TestClass
but in real life this requires changing many other classes.

I also tried adding
[assembly: InternalsVisibleTo("ClearScript")]
[assembly: InternalsVisibleTo("ClearScriptV8-64")]
[assembly: InternalsVisibleTo("ClearScriptV8-32")]
but that also didn't work.

Is there a reason why the property is accessible and the method is not?


Thanks a lot,
Ron
Coordinator
Mar 6, 2014 at 2:16 PM
Hi Ron,

Is there a reason why the property is accessible and the method is not?

Yes, it has to do with the way ClearScript binds to .NET type members. For most things it uses reflection, but for methods it uses the C# runtime binder. These facilities have different rules for accessing non-public resources.

Try using ScriptEngine.AccessContext. For example:
engine.AccessContext = typeof(Program);
From the ClearScript Library Reference: "By setting this property to a type you declare that script code running in the current script engine is to be treated as if it were part of that type's implementation. Doing so does not expose any host resources to script code, but it affects which host resources are importable and which members of exposed resources are accessible."

Hopefully this solution is practical in your actual scenario.

Good luck!
Marked as answer by Zcodez on 3/6/2014 at 7:46 AM
Mar 6, 2014 at 3:46 PM
Thanks for an immediate perfect answer, as always!

Ron