Jeff
Jeff

Reputation: 1242

Calling a Julia function from C++ that takes a Julia callback function as an argument

I'd like to call a Julia function from C++. This Julia function takes another Julia function as an argument (a callback function). I'd like to write this callback function entirely in C++ too, and pass it directly to Julia, without declaring a name for it in Julia's name space, like how other primitive types are passed. Presumably the arguments to my C++ implementation of the callback function will have jl_value_t * as their types.

Can anyone provide me with an example of how to do this? The embedded Julia example is pretty good, but it doesn't seem to illustrate this case.

Update: Revised and clarified based on Yakk's answer.

Upvotes: 1

Views: 1061

Answers (1)

Yakk - Adam Nevraumont
Yakk - Adam Nevraumont

Reputation: 275190

The example covers this case.

Here we call a c function:

jl_eval_string("println( ccall( :my_c_sqrt, Float64, (Float64,), 2.0 )

Which is defined at the top of the example.

Elsewhere there is an exampe of defining a julia function. Define one that does a ccall into your c code.

jl_eval_string("my_func(x) = 2*x");

(Except instead of 2*x it does ccall(blah)).

The take that julia function, and get a pointer to it (also in your linked example).

jl_function_t *func = jl_get_function(jl_base_module, "reverse!");

And pass it to the julia function expecting a callback. Or, use an eval to pass it by name.

The C++ code will be passed doubles and the like with this plan.

Upvotes: 1

Related Questions