# What is the best way to wrap C double pointers into a Julia Matrix?

Take this code which represents a matrix in C.

int** mat = (int**) malloc(rows * sizeof(int*))

for (int index=0;index<row;++index) {
mat[index] = (int*) malloc(cols * sizeof(int));
}


What is the best way to wrap mat into a Matrix{Float32}?

Right now, I came up with this solution:

result = Matrix{V}(undef, m, n)
rows = Base.unsafe_wrap(Vector{Ptr{V}}, mat, m)
@inbounds @simd for i in 1:length(rows)
result[i, :] = Base.unsafe_wrap(Vector{V}, rows[i], n)
end
return result


Any ideas on optimizing it?

This is not possible. An m \times n Julia Matrix is stored as a single linear array of length mn, with column-major ordering, not as an array of m pointers to m arrays of length n. Just like BLAS and LAPACK.

3 Likes

I think you have two options: either copy the data into a new matrix as you have or make an AbstractMatrix subtype which accesses the data directly (there might be a package for this).

Your code looks fine. I doubt that @simd is doing anything though but you could try explicitly copying each element. The implementation of the row copy probably uses simd anyway.

Probably it can be wrapped as a Vector{Vector{Int}}

2 Likes