C调用
可以使用ccall
或@ccall
调用C导出的库
调用时常常使用C
开头的类型名称,也会用到引用相关知识
ccall
原型是ccall((function_name, library), returntype, (argtype1, ...), argvalue1, ...)
或ccall(function_name, returntype, (argtype1, ...), argvalue1, ...)
或ccall(function_pointer, returntype, (argtype1, ...), argvalue1, ...)
,其中library是库的路径;每个argvalue
会通过unsafe_convert(argtype, cconvert(argtype, argvalue))
转化为argtype
类型实例
调用C标准库的示例(需注意,这些函数大多在Libc
模块中已有,无需自己ccall)
julia> ccall(:srand,Cvoid,(Cint,),0)
julia> ccall(:rand,Cint,())
38
一个调用windows api获取鼠标指针位置的示例:
mutable struct Point
x::Clong
y::Clong
end
julia> pt=Point(0,0)
Point(0, 0)
julia> ccall((:GetCursorPos,"User32.dll"),stdcall,Cint,(Ptr{Cvoid},),Ref(pt))
1
julia> pt
Point(681, 404)
@ccall
原型是@ccall library.function_name(argvalue1::argtype1, ...)::returntype
或@ccall function_name(argvalue1::argtype1, ...)::returntype
或@ccall $function_pointer(argvalue1::argtype1, ...)::returntype
julia> @ccall srand(0::Cint)::Cvoid
julia> @ccall rand()::Cint
38