And if you want to reduce memory allocations and your fields are all of the 
same type:

immutable Foo{T}
    a::T
    b::T
    c::T
end

# this always works also for mutables / varying fieldtypes:
typevec(a) = [a.(x) for x in names(a)]

# create initial view
typevec!(foo::Foo) = pointer_to_array(
    convert(Ptr{typeof(foo.a)}, 
pointer_from_objref(foo))+sizeof(typeof(foo.a)), 3)

# point to a different obj, reusing the view array
function typevec!(a, view)
    p = convert(Ptr{eltype(view)}, pointer_from_objref(view))
    unsafe_store!(p, pointer_from_objref(a)+sizeof(eltype(view)), 2)
    view
end

foo = Foo(1,2,3)
foo2 = Foo(10,20,20)
@show @time typevec(foo)
@show @time view = typevec!(foo)
@show @time typevec!(foo2,view)


Just be careful that foo does not go out of scope while you use the result of 
"typevec!"




Am 05.03.2015 um 11:00 schrieb Simon Danisch <[email protected]>:

> easiest would probably be: [foo.(i) for i=1:length(names(Foo))]
> 
> 
> Am Donnerstag, 5. März 2015 10:51:36 UTC+1 schrieb Tamas Papp:
> If I have a composite type 
> 
> type Foo 
>   a 
>   b 
>   c 
> end 
> 
> I can initialize it with a vector like this: 
> 
> x = Foo([1,2,3]...) 
> 
> But how can I get the fields as a vector, eg [x.a,x.b,x.c] without 
> enumerating them? convert(x, Vector) does not work. 
> 
> I need this to go back and forth between the type and the vector 
> representation of a set of parameters when using NLopt. 
> 
> Best, 
> 
> Tamas 

Reply via email to