Call Julia function with keywords from C++

Hi guys!

Let’s say I have Julia function:

function teste(a::Int,b::Int; c = 1.0, d = 1.0, e = 1.0)
    return (a+b)^(c+d+e)
end

How can I call it from C++ modifying the keyword d?

The only very dirty workaround I could think was to create a dummy function like:

teste_dummy(a,b,c) = teste(a,b;c=c)

Is it really the only way?

I found a better way by using the Core.kwfunc:

#include <iostream>

extern "C" {
#include <julia.h>
}

int main(int argv, char* argc[])
{
    jl_init();

    jl_function_t* teste = jl_eval_string("function teste(a;c = 1.0) \
            a+c \
            end");

    jl_function_t* kwsorter = jl_eval_string("Core.kwfunc");
    jl_function_t* testek = jl_call1(kwsorter,teste);

    jl_value_t* a = nullptr;
    jl_value_t* b = nullptr;
    jl_value_t* c = nullptr;

    JL_GC_PUSH3(a,b,c);

    a = (jl_value_t*)jl_box_float64(1.0);
    b = (jl_value_t*)jl_box_float64(1.0);
    c = (jl_value_t*)jl_eval_string("(c = 3.0,)");

    jl_value_t* ret = (jl_value_t*)jl_call3(testek,c,teste,a);

    std::cout << jl_unbox_float64(ret) << std::endl;

    JL_GC_POP();

    jl_atexit_hook(0);

    return 0;
}

Just need to find a way to create NamedTuples on C now.

Adding a cross reference to the issue and my tentative answer:
https://github.com/JuliaLang/julia/issues/31119#issuecomment-735109230

2 Likes