Call a foreign-language function: Difference between revisions

→‎Fiddle: Fix the code broken when Ruby 2.2 removed DL. Add second example using Fiddle::Importer.
(→‎{{header|CMake}}: Link is dead. Change it to man7)
(→‎Fiddle: Fix the code broken when Ruby 2.2 removed DL. Add second example using Fiddle::Importer.)
Line 1,733:
 
=== Fiddle ===
Fiddle is part of Ruby's standard library, and is another wrapper for libffi (different from the above FFI module). Fiddle replaces DL in the standard library. DL passed all C values as pointer-size integers, so it didn't work on some platforms. Fiddle uses libffi to pass C values as correct types. Ruby 1.9.2 added Fiddle to the standard library, but scripts needed to mix DL and Fiddle. Ruby 2.0 made Fiddle independent of DL. Ruby 2.2 removed DL, so old scripts don't work now.
Ruby 1.9.2 added Fiddle to the standard library. DL finds foreign functions, and Fiddle uses libffi to call them. DL and Fiddle are poorly documented. They are not compatible with all platforms.
 
{{works with|MRIRuby|12.9.20+}}
<lang ruby>require 'dlfiddle'
require 'fiddle'
 
# Declare strdup().
# * DL::Handle['strdup'] is the address of the function.
# * The function takes a pointer and returns a pointer.
strdup = Fiddle::Function.new(DL::Handle['strdup'],
[DL::TYPE_VOIDP], DL::TYPE_VOIDP)
 
# Find *strdup(). The functionIt takes a pointer and returns a pointer.
strdup = Fiddle::Function.new(DL::Handle['strdup'],
.new(Fiddle::Handle['strdup'],
[DLFiddle::TYPE_VOIDP], DLFiddle::TYPE_VOIDP)
# Call strdup().
# * Fiddle- It converts our Ruby string to a C string.
# * Fiddle- It returns a DLFiddle::CPtrPointer.
duplicate = strdup.call("This is a string!")
#puts DL::CPtr#duplicate.to_s converts our # Convert the C string to a Ruby string.
Fiddle.free duplicate # free() the memory that strdup() allocated.</lang>
 
Fiddle::Importer is also part of Ruby's standard library.
# DL::CPtr#to_s converts our C string to a Ruby string.
puts duplicate.to_s
 
{{works with|Ruby|2.0+}}
# We must call free(), because strdup() allocated memory.
<lang ruby>require 'fiddle'
DL.free duplicate</lang>
require 'fiddle/import'
 
module C
extend Fiddle::Importer
dlload Fiddle::Handle::DEFAULT
extern 'char *strdup(char *)'
end
 
duplicate = C.strdup("This is a string!")
puts duplicate.to_s
DLFiddle.free duplicate</lang>
 
=== RubyInline ===
Anonymous user