2
0

More than 3 years have passed since last update.

Ruby-FFI で argv[] のような「C言語の文字列の配列」を扱いたい時の書き方

Last updated at Posted at 2020-08-19

こちらのサイトによると(2009年の情報なので情報が古いかも知れないけれども)
https://zegoggl.es/2009/05/ruby-ffi-recipes.html

下のような関数定義があったときに

int execvp(const char *file, char *const argv[]);

Ruby-FFIはこう書く。

module Exec
  extend FFI::Library
  attach_function :execvp, [:string, :pointer], :int
end

使う時は…

strptrs = []
strptrs << FFI::MemoryPointer.from_string("vim")
strptrs << FFI::MemoryPointer.from_string("/tmp/foo")
strptrs << nil

# Now load all the pointers into a native memory block
argv = FFI::MemoryPointer.new(:pointer, strptrs.length)
strptrs.each_with_index do |p, i|
    argv[i].put_pointer(0,  p)
end

Exec.execvp("vim", argv)

読めば何をしているすぐかわかるけど、少々面倒。

もっといい方法をご存知でしたら是非コメント欄へ。

この記事は以上です。

2
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
2
0