Show how to call a function in a shared library (without dynamically linking to it at compile-time). In particular, show how to call the shared library function if the library is available, otherwise use an internal equivalent function.

This is a special case of calling a foreign language function where the focus is close to the ABI level and not at the normal API level.



Related task

 OpenGL -- OpenGL is usually maintained as a shared library.


libm = LibC.dlopen("libm.so.6", LibC::RTLD_LAZY)
sqrtptr = LibC.dlsym(libm, "sqrt") unless libm.null?
 
if sqrtptr
  sqrtproc = Proc(Float64, Float64).new sqrtptr, Pointer(Void).null
  at_exit { LibC.dlclose(libm) }
else
  sqrtproc = ->Math.sqrt(Float64)
end
 
puts "the sqrt of 4 is #{sqrtproc.call(4.0)}"