C union style for julia

Hi,
Is there something equivalent to C union in Julia?

Example:

union {
  double b;
  uint64_t u64;
} u;
u.b = d;
// use u.u64 here ....

I found the following package:

Is this the way the community would suggest to do it? Or is there a Julia base version which is recommended?

Thank you

1 Like

Not in the sense, that the memory size for this union is the same for all values allowed by the union definition (afaik). But there is Type-Unions:
https://docs.julialang.org/en/v1/manual/types/#Type-Unions

To answer this, you need to tell us something about your problem/task/algorithm. There is no Julia way to do just the same as C union without a context.

CUnion.jl seems to implement the C union property like memory size is the largest type, so it seems to be it. But I don’t know if this is really needed.

2 Likes

No; you need to do something like

julia> mutable struct U
       u64::UInt64
       end
julia> Base.getproperty(u::U, s::Symbol) = s == :b ? reinterpret(Float64, getfield(u, :u64)) : getfield(u, s)
julia> Base.setproperty!(u::U, s::Symbol, b) = s == :b ? setproperty!(u, :u64, reinterpret(UInt64, b)) : setfield!(u, s, b) 
julia> u = U(1)
U(0x0000000000000001)
julia> u.b
5.0e-324
julia> u.b = -1.0
-1.0
julia> u 
U(0xbff0000000000000)
1 Like

Thank you. To give a bit of context, I am trying to build a faster unique function similar to this one:

You should have a look at GitHub - analytech-solutions/CBinding.jl: Automatic C interfacing for Julia for working with user-defined C types in Julia, especially if they are already defined in a header file.

1 Like