[前][次][番号順一覧][スレッド一覧]

ruby-changes:65349

From: Aaron <ko1@a...>
Date: Sat, 27 Feb 2021 02:59:14 +0900 (JST)
Subject: [ruby-changes:65349] 0590e9b677 (master): Fiddle::Function responds to to_proc

https://git.ruby-lang.org/ruby.git/commit/?id=0590e9b677

From 0590e9b677e8c0b7a2364f660f06d9f5bd8fe87d Mon Sep 17 00:00:00 2001
From: Aaron Patterson <tenderlove@r...>
Date: Fri, 26 Feb 2021 09:57:13 -0800
Subject: Fiddle::Function responds to to_proc

This lets us cast a Fiddle::Function to a block, allowing is to write
things like:

```ruby
f = Fiddle::Function.new(@libc['strcpy'], [TYPE_VOIDP, TYPE_VOIDP], TYPE_VOIDP)
define_method :strcpy, &f
```
---
 ext/fiddle/lib/fiddle/function.rb |  5 +++++
 test/fiddle/test_function.rb      | 13 +++++++++++++
 2 files changed, 18 insertions(+)

diff --git a/ext/fiddle/lib/fiddle/function.rb b/ext/fiddle/lib/fiddle/function.rb
index 0f9913a..f9910a0 100644
--- a/ext/fiddle/lib/fiddle/function.rb
+++ b/ext/fiddle/lib/fiddle/function.rb
@@ -19,5 +19,10 @@ module Fiddle https://github.com/ruby/ruby/blob/trunk/ext/fiddle/lib/fiddle/function.rb#L19
     def to_i
       ptr.to_i
     end
+
+    # Turn this function in to a proc
+    def to_proc
+      lambda { |*args| self.call(*args) }
+    end
   end
 end
diff --git a/test/fiddle/test_function.rb b/test/fiddle/test_function.rb
index 742615a..5dc456b 100644
--- a/test/fiddle/test_function.rb
+++ b/test/fiddle/test_function.rb
@@ -102,6 +102,19 @@ module Fiddle https://github.com/ruby/ruby/blob/trunk/test/fiddle/test_function.rb#L102
       assert_equal("123", str.to_s)
     end
 
+    def call_proc(string_to_copy)
+      buff = +"000"
+      str = yield(buff, string_to_copy)
+      [buff, str]
+    end
+
+    def test_function_as_proc
+      f = Function.new(@libc['strcpy'], [TYPE_VOIDP, TYPE_VOIDP], TYPE_VOIDP)
+      buff, str = call_proc("123", &f)
+      assert_equal("123", buff)
+      assert_equal("123", str.to_s)
+    end
+
     def test_nogvl_poll
       # XXX hack to quiet down CI errors on EINTR from r64353
       # [ruby-core:88360] [Misc #14937]
-- 
cgit v1.1


--
ML: ruby-changes@q...
Info: http://www.atdot.net/~ko1/quickml/

[前][次][番号順一覧][スレッド一覧]