Skip to content

feat: implement NEXO API in C# lib #283

@Thyodas

Description

@Thyodas

Objective

We need to implement most of our API in our C# managed lib, for example GetComponent and so on.

Acceptance Criteria

  • 1. See subissues for each functions to implement

Dependencies

No response

Technical Details

To implement new NEXO API in C# you should look at the following

Callbacks on C++ side

In file engine/src/scripting/native/NativeApi.hpp you'll find all callbacks callable by the C# NEXO lib.

To add a new callback follow these steps

  1. Just create a function in the .hpp in extern "C" block with this format:
    NEXO_RET(<RETURN TYPE>) <FUNCTION NAME>(<ARG TYPE 1>, <ARG TYPE 2>); where should be replaced with right value, for example NEXO_RET(Int32) NxAddNumbers(Int32 a, Int32 b);

Tip

Int32, Vector3 ... are native C# types, I made a ManagedTypedef.hpp declaring types in C++ to be equivalent to C# for better compatibility.

Warning

From now on, when implementing new API, we should make the API functions name start with Nx, because they are native C functions and don't have an namespace

  1. Add a new entry to struct NativeApiCallbacks, like ApiCallback<Int32(Int32, Int32)> NxAddNumbers{&scripting::AddNumbers};, ApiCallBack is just a function pointer wrapper, do not forget the default value in {} brackets, it won't compile without to guarantee that a function pointer has been set for this field.

Now everything is good on the C++ side. These callbacks will be initialized automatically at launch and sent to the C#.

Callbacks on C# side

Now for the C# side, you'll find a file called engine/src/scripting/managed/NativeInterop.cs.

That's were the native callbacks are defined.

To add one follow these steps

  1. In private struct NativeApiCallbacks add new fields,

    1. One for delegate, the type of the function pointer
    [UnmanagedFunctionPointer(CallingConvention.Winapi, CharSet = CharSet.Ansi)]
    public delegate Int32 NxAddNumbersDelegate(Int32 a, Int32 b);
    1. And then one for the struct field, the implementation of the function pointer
    public NxAddNumbersDelegate NxAddNumbers;
  2. Create a wrapper to call this new callback

public static Int32 AddNumbers(Int32 a, Int32 b)
{
    try
    {
        return s_callbacks.NxAddNumbers.Invoke(a, b);
    }
    catch (Exception ex)
    {
        Logger.Log(LogLevel.Error, $"Error calling NxAddNumbers: {ex.Message}");
        return 0;
    }
}

Now you're all done, you can try calling this wrapper in any C# function, like DemonstrateNativeCalls and so on.

Type

Engine

Metadata

Metadata

Labels

No labels
No labels

Type

Projects

Status

In Progress

Milestone

No milestone

Relationships

None yet

Development

No branches or pull requests

Issue actions