Ruby FFI(メモ)
https://www.google.co.jp/search?q=ruby+ffi
Ruby FFIを使ったエクステンションの作り方 - Boost Your Programming!
Ruby-FFIについて調べてみた。(まとめ) - いものやま。
ffi | RubyGems.org | your community gem host
c - How do I handle ruby arrays in ruby ffi gem? - Stack Overflow
例
c - How do I handle ruby arrays in ruby ffi gem? - Stack Overflow
ここのとおりにやってみる。
my_c_lib.c
#include <stdlib.h> double *my_function(double array[], int size) { int i = 0; double *new_array = malloc(sizeof(double) * size); for (i = 0; i < size; i++) { new_array[i] = array[i] * 2; } return new_array; }
$ mkdir for_ffi $ cd for_ffi $ gcc -Wall -fPIC -c my_c_lib.c -o my_c_lib.o $ gcc -shared -o my_c_lib.so my_c_lib.o $ cd ..
my_c_lib.rb
require 'bundler/setup' require 'ffi' module MyModule extend FFI::Library # Assuming the library files are in the same directory as this script ffi_lib "./for_ffi/my_c_lib.so" attach_function :my_function, [:pointer, :int], :pointer end array = [4, 6, 4] size = array.size offset = 0 # Create the pointer to the array pointer = FFI::MemoryPointer.new(:double, size) # Fill the memory location with your data pointer.put_array_of_double(offset, array) # Call the function ... it returns an FFI::Pointer result_pointer = MyModule.my_function(pointer, size) # Get the array and put it in `result_array` for use result_array = result_pointer.read_array_of_double(size) # Print it out! p result_array
実行。
$ ruby my_c_lib.rb [8.0, 12.0, 8.0]
OK ですね!