Embedded Julia segmentation fault when loading BSON file

Thanks for the answer! I got it to run as expected.

I think part of my problem is that there seems to be an issue with BSON inside modules as well: https://github.com/FluxML/Flux.jl/issues/1322
So Julia did throw an error which I didn’t caught or checked for in the C code.

Here is now my working code:

C code

#include <stdio.h>
#include <stdlib.h>
#include <julia.h>

JULIA_DEFINE_FAST_TLS // only define this once, in an executable (not in a shared library) if you want fast code.

int main(int argc, char *argv[]){
  /* Variables */
  jl_function_t *loadVar = NULL;
  jl_function_t *evalFunc = NULL;
  jl_value_t* array_type = NULL;
  jl_array_t *jl_inputs = NULL;
  jl_array_t *jl_outputs = NULL;
  jl_value_t *jl_filename = NULL;

  /* required: setup the Julia context */
  jl_init();

  /* GC rooting */
  JL_GC_PUSH6(&loadVar, &evalFunc, &array_type, &jl_inputs, &jl_outputs, &jl_filename);

  jl_eval_string("Base.include(Main, \"mwe.jl\")");
  jl_eval_string("using Main.MWE");
  jl_module_t* MWE = (jl_module_t *)jl_eval_string("Main.MWE");

  /* Get loadNN and evalNN function */
  loadVar = jl_get_function(MWE, "loadVar");
  evalFunc = jl_get_function(MWE, "evalFunc");

  /* Create thin wrapper around arrays */
  array_type = jl_apply_array_type((jl_value_t*)jl_float64_type, 1);

  size_t length_inputs = 2;
  double *inputs = (double*)calloc(length_inputs, sizeof(double));
  jl_inputs = jl_ptr_to_array_1d(array_type, inputs, length_inputs, 0);

  size_t length_outputs = 2;
  double *outputs = (double*)calloc(length_outputs, sizeof(double));
  jl_outputs = jl_ptr_to_array_1d(array_type, outputs, length_outputs, 0);

  /* Load data from BSON */
  const char filename[]= "savedVar.bson";
  jl_filename = jl_cstr_to_string(filename);
  jl_call1(loadVar, (jl_value_t*)jl_filename);

  /* Evaluate NN */
  jl_call2(evalFunc, (jl_value_t*)jl_inputs, (jl_value_t*)jl_outputs);

  /* Release GC roots */
  JL_GC_POP();

  /* Notify Julia that programm is going to end */
  jl_atexit_hook(0);
  return 0;
}

Julia code

module MWE
  using BSON
  using BSON: @save

  export loadVar
  export saveVar
  export evalFunc

  function saveVar(modelFile::String)
    someVar = [1.0, 2.0]
    @save abspath(modelFile) someVar
  end

  function loadVar(modelFile::String)
    @info "Loading var from \"$(modelFile)\""
    someVar = "missing"
    try
      someVar = BSON.load(abspath(modelFile),  @__MODULE__)[:someVar]
    catch err
      println(err)
    end
    println("someVar: ", someVar)
  end

  function evalFunc(inputs::Array{Float64}, outputs::Array{Float64})
    @info "Inputs $(inputs)"
    @info "Outputs $(outputs)"
  end
end
$ ./mwe 
[ Info: Loading var from "savedVar.bson"
someVar: [1.0, 2.0]
[ Info: Inputs [0.0, 0.0]
[ Info: Outputs [0.0, 0.0]