Understanding How Ruby Handles an Array of Ruby to Dll and Receives an Array Processed by Dll in Ruby

Asked 2 years ago, Updated 2 years ago, 111 views

I created the following dll in C language.

void example(int*a)
{
 for(inti=0;i<10;++i){
  a[i]+=1;
 }
}

How can I pass the ruby array hoge[0,0,0,0,0,0,0,0] to this dll and receive the processed array hoge'[1,1,1,1,1,1,1] on the ruby side?

The dll call is

Win32 API.new(DLL_NAME, 'example', 'p', 'v')

is used.

I look forward to hearing from you.

ruby c array

2022-09-29 21:21

1 Answers

I don't have windows, so I'm sorry for the mac information, but ruby2.2.0 was done below.

#test.rb
require "fiddle/import"
module M
  extend Fiddle::Importer
  dload "libtest.dylib"
  external "void example(int*a)"
end

hoge=[0]*10
hoge
hoge=hoge.pack('i*')
M.example(hoge)
hoge.unpack('i*')

The results are as follows:

$ruby test.rb
[0, 0, 0, 0, 0, 0, 0, 0, 0, 0]
[1, 1, 1, 1, 1, 1, 1, 1, 1, 1]

From ruby 2.2, I heard that they use fiddles.I think it can also be used on Windows.

library fiddle
Library for handling dynamic link libraries, such as .dll and .so.

http://docs.ruby-lang.org/ja/2.1.0/library/fiddle.html

I am using pack, unpack because it seems that it needs to be converted into a string to exchange arrays.

I want to pass the array of ○○ to the function
If you want to invoke this, use Array#pack as follows:

http://docs.ruby-lang.org/ja/2.0.0/library/fiddle=2fimport.html


2022-09-29 21:21

If you have any answers or tips


© 2024 OneMinuteCode. All rights reserved.