Accessing C Array in Julia

embedding

#1

How do I access Array of Strings from C in Julia?

Here is the C Code

int main(int argc, char *argv[]){
	compute_sum(argv[1], argv[2]);
	return 1;
}

void compute_sum(char* val1, char* val2){
	jl_init(JULIA_INIT_DIR);
	jl_value_t* array_type = jl_apply_array_type(jl_string_type, 1);
	jl_array_t* x = jl_alloc_array_1d(array_type, 2);

	char *xData= (char*)jl_array_data(x);

	xData[0] = *val1;
	xData[1] = *val2;
	jl_load("mymodule.jl");
	jl_value_t* mod = (jl_value_t*)jl_eval_string("mymodule");
	jl_function_t *func = jl_get_function((jl_module_t*)mod,"sum");
	jl_value_t *ret = jl_call1(func, (jl_value_t*)x);
	if (jl_exception_occurred())
		printf("%s \n", jl_typeof_str(jl_exception_occurred()));
	jl_atexit_hook(0);
}

How to write corresponding Julia function to receive the array and process it?
Also how to access the returned value?

Function in Julia:

function sum(A){
      typeof(A)
      return 25
}

Output:

DataType

#2

function sum(A){

No braces.

jl_value_t* mod = (jl_value_t*)jl_eval_string(“mymodule”);

Your julia file doesn’t define mymodule, so you need to use jl_main_module (or actually do define the module).

char xData= (char)jl_array_data(x);
xData[0] = *val1;

Not clear what you are trying to do here:

  • *val1 is dereferencing the target so you just get the first character. (also: in ASCII, so getting chars directly from argv will not work as expected).
  • x is a char*, you can’t stick multiple char* inside of it anyway.

Here’s a simplified example with some corrections. General advice is to get really familiar with Julia before trying to do any embedding (likewise C).

int64_t compute_sum(int64_t val1, int64_t val2){
    jl_value_t* array_type = jl_apply_array_type((jl_value_t*)jl_int64_type, 1);
    jl_array_t* x = jl_alloc_array_1d(array_type, 2);
    jl_value_t *ret;

    int64_t* xData = (int64_t*)jl_array_data(x);
    xData[0] = val1;
    xData[1] = val2;

    JL_GC_PUSH2(&x, &ret);
    jl_load("mymodule.jl");
    jl_function_t *func = jl_get_function(jl_main_module,"sum");
    ret = jl_call1(func, (jl_value_t*)x);

    int64_t rval = jl_unbox_int64(ret);
    JL_GC_POP();

    return rval;
}

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

    int64_t res = compute_sum(12, 17);

    if (jl_exception_occurred())
    	printf("%s \n", jl_typeof_str(jl_exception_occurred()));
    else
        printf("result: %lld\n", res);

    jl_atexit_hook(0);
    return 1;
}
function sum(a::Vector{Int64})
    res = 0
    for x in a
        res += x
    end
    res::Int64
end