microsoft / node-api-dotnet

Advanced interoperability between .NET and JavaScript in the same process.
MIT License
524 stars 58 forks source link

[JSExport] and namespace #209

Closed james-hu closed 8 months ago

james-hu commented 9 months ago

I have a class inside a namespace on dotnet side. Without [JSExport], I can reference the class in Javascript as dotnet.MyNameSpace.MyClass. It works.

I tried to use [JSExport] on that class. The generated .d.ts requires the class to be referenced as dotnet.MyClass. However, when I run the code, the error message says MyClass does not exist on dotnet.

jasongin commented 9 months ago

There are two approaches to calling .NET from JS, and it sounds like you might be mixing them up.

  1. Create a node module in C#, tag exported classes/methods with [JSExport], then import your module directly in JS, and use the APIs like you would any other JS module. The marshalling code is generated at build time by the analyzer. The exported module APIs are not in any .NET namespace and would not be accessed via the dotnet object.
  2. Dynamically load and invoke .NET APIs from JS. This does not depend on any use of [JSExport]; the marshalling code is generated at runtime via reflection. APIs for all loaded .NET assemblies are in namespaces under the dotnet object.
james-hu commented 9 months ago

Thanks for the explanation. I've tried diffrent approaches and below are my findings.

Through method 1, with [JSExport]

Through method 1, without [JSExport]

Through method 2, ( [JSExport] is not supported and has no effect )

And, code generation in method 1 seems to be broken (see #207 )

jasongin commented 8 months ago

Code generation does not work out-of-the-box with .NET SDK 6, it seems to work better with .NET SDK 8

This was recently fixed by #215.

I'm closing this issue since all the individual problems are tracked by other issues.