JuliaArrays / StaticArrays.jl

Statically sized arrays for Julia
Other
763 stars 148 forks source link

Mapping SVector/SMatrix to static arrays in C Structs #340

Closed klowrey closed 6 years ago

klowrey commented 6 years ago

I recently wrapped a C library for use in Julia that made heavy use of structs. Long story short, it can still be some ugly point manipulation, but it's at a reasonably usable state. One issue I just discovered was wrapping static arrays in C structs with StaticArrays in immutable Julia structs. This makes much more sense than trying to allocate the space with NTuples, plus it's more useable from a data access perspective.

Lets take the following example struct in Julia 0.6.1

// in C
struct foo {
  int a[2];
  int b[2][2];
}
# in julia
immutable foo
  a::SVector{2, Cint}
  b::SMatrix{2, 2, Cint}
end

I would expect that this would wrap the c struct with the same memory layout (b is 2x2 to avoid col-major row-major), but what happens is segfaults when trying to allocate or access this data through the c library. What I think this boils down to is:

julia> isbits(SVector{2,Cint})
true

julia> isbits(SMatrix{2,2,Cint})
false

julia> x = SMatrix{2,2,CInt}(rand(2,2)); isbits(x)
true

An SVector type results in fixed memory size, but not the SMatrix. A declared/allocated SMatrix, however, works as expected, but I can't set a field in an immutable as a variable.

1) is this expected behavior for SMatrix? It surprised me; SVector worked as expected for all other fields in use. 2) if this is expected behavior, is there any other way to wrap the fields in the c struct appropriately?

Thanks all.

c42f commented 6 years ago

The problem is that the fully parameterized type of SMatrix requires the total number of elements. (This is an unfortunate implementation detail which we couldn't figure out how to remove.)

So you need to use SMatrix{2,2,Cint,4} (note the trailing 4):

julia> isbits(SMatrix{2,2,Cint,4})
true
andyferris commented 6 years ago

Yes, the 4 here is crucial or you get something with complete different layout (a Julia boxed object).

klowrey commented 6 years ago

Thanks for pointing this out; totally fixes my issue.