Ccall with a C struct containing a pointer

Great! Thank you: answer accepted. I’ve expanded that snippet into a self-contained example, for posterity:

mutable struct DenseMatrix # layout matches the C.
    rowCount::Cint
    columnCount::Cint
    data::Ptr{Cdouble}
end
function Base.cconvert(::Type{DenseMatrix}, m::Matrix{Float64})
    return (m, DenseMatrix(size(m)[1], size(m)[2], C_NULL))
end
function Base.unsafe_convert(::Type{DenseMatrix}, tup::Tuple{Matrix{Float64}, DenseMatrix})
    m, dm = tup
    dm.data = pointer(m) # m is GC-preserved in this function, so this is safe
    return dm
end
function CWrapper(arg1::Matrix{Float64}) # Julia base type here...
    @ccall lib.fname(arg1::DenseMatrix) # ...and C struct type here.
end

It’d be good to get a more elaborate example like this in the docs.

1 Like