I am trying to familiarize with calling C functions from Julia.
I have some troubles with easy functions like isalnum.
Running
ccall( (:isalnum, "libc"), Bool, (ASCIIString,), "k")
Returns always false.
I also tried to use the function "div" which returns quotient and reminder of a division. To store both values I created a type
type Foo
A::Int64
B::Int64
end
and then run
t = ccall( (:div, "libc"), Foo, (Int64,Int64,), 7,3)
but the results are wrong.
Unfortunately, Julia doesn't currently support returning structs from ccalls. There is an open pull request implementing this that fell through the cracks during the 0.3 release cycle and didn't get merged. If this were supported (it will be soon on the master branch), you would use an immutable structure to make it work. Like this:
julia> immutable Cdiv_t
q::Cint
r::Cint
end
julia> ccall(:div, Cdiv_t, (Cint,Cint), 7, 3)
Cdiv_t(2,2)
As you can see, this is broken because the remainder part of the Cdiv_t structure is incorrect (it will currently always be the same as the quotient part). It's necessary to use an immutable structure because a mutable structure needs to store its components on the heap as individually allocated values – which is not compatible with C struct layout. Since Cdiv_t is immutable, its components can be stored inline, which is how C does it.
Also note the use of Cint as the Julia-side mirror of the C int type. This is always defined so that it is the correct type corresponding to C's int type – which is not always so easy to determine. The chapter on calling C and Fortran contains a full list of Julia types that correspond to C types. You generally want to use the middle column names in your Julia code since they will work anywhere, not just on your system.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With