I’m a Crystal newbie and I am trying to create my first C binding but there’s a few aspects I don’t quite understand…
First, how do I pass a pointer to a structure? This is what I’m attempting:
# the structure
struct XlsxDateTime
year : Int32
month : Int32
day : Int32
hour : Int32
min : Int32
sec : Float64
end
# the function signature
fun worksheet_write_datetime(worksheet : UInt64, row : UInt32, col : UInt16, datetime : XlsxDateTime*, format : UInt64) : UInt32
# and this is how I'm trying to call it
dt = Xlsx::XlsxDateTime.new
dt.day = 8
dt.month = 5
dt.year = 2025
Xlsx.worksheet_write_datetime(ws, row, col, Pointer(dt), fd)
Another general tip is that lifetimes matter. So if you take a pointer to a local variable, then you must not let the current scope be invalidated. So especially when it comes to defining callbacks that is not an option, and instead you will probably want to define something like
I’d recommend to take a deeper look at the language reference: About this guide - Crystal, especially the sections about C bindings and unsafe code. There are a couple of traps on the way.
For example, the struct definition should either be inside a lib or annotated as @[Extern] so the compiler preserves the layout as defined.