n-api-article icon indicating copy to clipboard operation
n-api-article copied to clipboard

building multiple functions

Open xthdraft opened this issue 7 years ago • 1 comments

I had no problem building your example and running it in my electron app. However, all of the tutorials I've come across only demonstrate building a single file referenced from binding.gyp, despite the "sources":[] field in binding.gyp seemingly allowing multiple source.files.

It would be immensely helpful if you would expand your tutorial to show how to build a case with something like: "sources": [ "src/binding.c", "src/anotherexample.c" ]

Many thanks for your fine tutorial.

xthdraft avatar Nov 02 '18 05:11 xthdraft

I have a file, module.c, where I want to import two functions to use from native code. They are defined respectively in two separate files so I include them in module.c as two different header files. I've done the following with the binding.gyp file and the init function inside of module.c

binding.gyp

{
    "targets": [
        {
            "target_name": "module",
            "sources": ["../c/module.c", "../c/HammingDistance.c", "../c/Multiplication.c"]
        }
    ]
}

module.c

napi_value Init(napi_env env, napi_value exports)
{
    napi_status status;
    napi_value fn;

    status = napi_create_function(env, NULL, 0, HammingDistanceNative, NULL, &fn);

    if (status != napi_ok)
    {
        napi_throw_error(env, NULL, "Unable to wrap native function");
    }

    status = napi_set_named_property(env, exports, "calcHammingDistance", fn);

    if (status != napi_ok)
    {
        napi_throw_error(env, NULL, "Unable to populate exports with calcHammingDistance");
    }

    status = napi_create_function(env, NULL, 0, MultiplyTwoNumbersNative, NULL, &fn);

    if (status != napi_ok)
    {
        napi_throw_error(env, NULL, "Unable to wrap native function");
    }

    status = napi_set_named_property(env, exports, "multiplyTwoNumbers", fn);

    if (status != napi_ok)
    {
        napi_throw_error(env, NULL, "Unable to populate exports with multiplyTwoNumbers");
    }

    return exports;
}

SirGoose3432 avatar Feb 10 '19 23:02 SirGoose3432