Anonymous user
Call a foreign-language function: Difference between revisions
Call a foreign-language function (view source)
Revision as of 02:40, 20 September 2017
, 6 years ago→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.
{{works with|
<lang ruby>require '
require 'fiddle'▼
# * The function takes a pointer and returns a pointer.▼
strdup = Fiddle::Function.new(DL::Handle['strdup'],▼
[DL::TYPE_VOIDP], DL::TYPE_VOIDP)▼
.new(Fiddle::Handle['strdup'],
# Call strdup().
#
#
duplicate = strdup.call("This is a 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+}}
<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
=== RubyInline ===
|