简体   繁体   中英

Boxing/Unboxing complex types in Julia

I have basically digged through all Julia documentation, but I cannot find any answers on this. My question can be split into two parts. Code snippets ignore stuff like basic s initialization.

Part 1: How to pass basic complex types without jl_eval_string()

Suppose I have a C/C++ program which calls some Julia scripts, for a function f which do some String manipulation. In the C source:

char* parameter_string; // Initialized as something.
jl_module_t *m = (jl_module_t *) jl_load("Script.jl");
jl_function_t *f = jl_get_function(m, "f");
jl_value_t * ret = jl_call1(f, /*???*/) <--- Problem

Now, notice that the manual only describes how to box up primitives, like int, float, double. Nothing about complex types, like String . Yes, I can use jl_eval_string(parameter_string) , but I don't like this. Moreover, ret will be a String, and I have no idea how to extract it to C. It is undocumented.

Part 2:

Suppose I have a C/C++ program which calls some Julia scripts, in which a state machine is stepped. To create a state machine, I create some types:

abstract State
type Idle <: State end
type State1 <: State end
type State2 <: State end

And then a transition function:

function transition(s :: State, input :: String) # input :: String is arbitrary
  .. Do Something ..
  return newState
end

Now, if I want to create a State , say Idle , in C... I cannot find anything like this, let alone finding a way to retrieve it from Julia.

I am approaching this problem more or less like functional programming language, such as Haskell, Scala, or F#. Algebraic Data Type might not be well supported here, but I think it is still better than hard coding it with integers.

The real problem is that I cannot find any C API documents on Julia, without directly digging into its source code.

You can convert a C string to a Julia String using jl_cstr_to_string(char*) .

To get the data from a Julia String , use jl_string_ptr(jl_value_t*) .

Constructors are called just like functions, so to call a constructor you can use jl_get_function(m, "Idle") and call it as normal. Or, to allocate an object directly (going around any constructors that might be defined, so technically a bit dangerous), you can call jl_new_struct(type, fields...) .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM