Call a julia function from a larger fortran program

When working with different programming languages, it is common to have the need to call functions from one language in another. In this case, the task is to call a Julia function from a larger Fortran program. There are several ways to achieve this, and in this article, we will explore three different options.

Option 1: Using the C Interface

One way to call a Julia function from Fortran is by using the C interface. Julia provides a C API that allows us to interact with Julia code from C or Fortran. To use this option, we need to write a C wrapper function that calls the Julia function and then call this wrapper function from Fortran.


#include <julia.h>

// C wrapper function
void call_julia_function(int arg1, int arg2) {
    jl_function_t *func = jl_get_function(jl_base_module, "my_julia_function");
    jl_value_t *args[2];
    args[0] = jl_box_int32(arg1);
    args[1] = jl_box_int32(arg2);
    jl_call(func, args, 2);
}

In the above code, we include the Julia header file and define a C wrapper function called call_julia_function. Inside this function, we get a reference to the Julia function using jl_get_function and then call it using jl_call. We pass the arguments to the Julia function using jl_box_int32 to convert them to Julia values.

In the Fortran program, we can then call the C wrapper function:


program main
    implicit none
    interface
        subroutine call_julia_function(arg1, arg2) bind(C)
            use iso_c_binding
            integer(c_int), value :: arg1, arg2
        end subroutine
    end interface

    ! Call the Julia function
    call call_julia_function(10, 20)
end program

This option requires writing a C wrapper function and using the C interface, which adds some complexity to the code. However, it provides a direct way to call Julia functions from Fortran.

Option 2: Using the Command Line

Another option is to call the Julia function from the Fortran program using the command line. We can use the system function in Fortran to execute a command, and we can invoke the Julia interpreter with the necessary arguments to call the function.


program main
implicit none

! Call the Julia function using the command line
call system("julia -e 'include("my_julia_script.jl""); my_julia_function(10

Rate this post

Leave a Reply

Your email address will not be published. Required fields are marked *

Table of Contents