ialex32x / unity-jsb

It brings Javascript runtime capability to Unity3D by integrating QuickJS.
MIT License
337 stars 41 forks source link

Possible to generate bindings/typings for custom .dlls? #37

Closed jeremywho closed 3 years ago

jeremywho commented 3 years ago

I have a custom dll that I'd like to use in typescript. Is it possible to generate bindings/types for that?

One other thing that is not clear to me is how to use c#<->typescript bindings. Do I just add a @ScriptType() decorator to my typescript classes to make them available in c#?

ialex32x commented 3 years ago

If it's a managed dll, you could directly expose all types in it. This process looks like:

using System.Reflection;

namespace Example.Editor
{
    using QuickJS.Binding;

    public class CustomBinding : AbstractBindingProcess
    {
        public override string GetBindingProcessName()
        {
            return "dotnetcore";
        }

        public override void OnPreExporting(BindingManager bindingManager)
        {
            bindingManager.AddExportedType(typeof(System.Math));
        }

        public override void OnPostExporting(BindingManager bindingManager)
        {
            bindingManager.ExportTypesInAssembly(typeof(System.Threading.Thread).Assembly, true);
            bindingManager.ExportTypesInAssembly(typeof(System.Console).Assembly, true);
        }
    }
}

Or if it's a native dll/so, there is no way to achive it at the moment, you need to write some glue code.

ialex32x commented 3 years ago

For C# Types, they could be exposed to typescript by adding [QuickJS.JSType] attribute or exporting by bindingManager.AddExportedType in CustomBinding process.

There is no easy way to access typescript classes reversely in C#.

The @ScriptType() decorator is used to mark the MonoBehaviour classes implemented in typescript, then The editor will be able to list these classes in an editor search box. (If you add JSBehaviour or JSBehaviourFull component to a GameObject, you can directly select a typescript class from a search box) There is an example about this feature, you could read example_monobehaviour.ts and my_class_inspector.ts for details. Another example is Assets/Examples/Resources/prefab/game_stage.prefab, you can add a typescript MonoBehaviour class to a game object. It's very similar to what you can do in C#.