Problem with dynamic Type

May 9, 2014 at 4:33 PM
hi, i have this source:

i add this class to the engine:
se.AddHostType("NativeLibraryImporter", typeof(DynamicDllImport));
dynamic c =  js.Evaluate(@"var o = new NativeLibraryImporter(""user32.dll"");");
but c is undefined, and when i use MessageBox function with o.MessageBox then i get error: method.
it work with c#, what is wrong?

thank you
May 9, 2014 at 9:36 PM
Hi furesoft,

First of all, wow, that is some interesting code! A dynamic class for invoking native methods? Very clever.

Unfortunately, there are a few issues:
  • In the above, the variable c is undefined because JavaScript statements (var in this case) don't have results. If you remove "var", you'll have an assignment expression, which has a result and is probably what you want.
  • At line 54 your class uses reflection to retrieve a private field from the binder. ClearScript's binder doesn't have a field with that name. As written, the code probably works only with a specific binder implementation.
  • DynamicDllImportMetaObject needs to provide an appropriate override for DynamicMetaObject.GetDynamicMemberNames(). JavaScript-style method invocation cannot work without it. Unfortunately there's no .NET API for enumerating native DLL exports.
  • Finally, there's a subtle bug in ClearScript that would prevent this from working even if all the other issues were resolved. We'll fix that ASAP.
Good luck!
May 10, 2014 at 4:05 AM
how can i get the method names from native dll?

idk how, its not my wrapper
May 10, 2014 at 2:46 PM
Unfortunately it isn't very simple. Have a look here.

Alternatively, you can just fake it. Consider changing your class so that the client code must specify what native methods it intends to call:
user32 = new NativeLibraryImporter('user32.dll', 'MessageBox', 'MessageBeep' /* etc */);
The class would just store those names and return them from GetDynamicMemberNames().