1

Ruby C拡張を実装しました(つまり、RubyスクリプトからC関数を呼び出します)以下は、ファイル「cFile.c」からcで実装された関数です

#include<stdio.h>
static VALUE cFunction(VALUE self, VALUE src)
{
   if(TYPE(str) == T_STRUCT)
   {
      printf(" variable str is of STRUCT type \n");
   }
   // here how can i get the members of structure variable "str" 

   return Qnil;
}
void Init_MyRuby()
{
    VALUE MRuby = rb_define_module("MyRuby");
    rb_define_singleton_method(MRuby, "cFunction", cFunction, 1);
} 

以下は、struct 型の変数を渡して functon() メソッドを呼び出す ruby​​ スクリプトのコードです。client.rb:

require 'cFile'
customer = Struct.new( "Customer", :name, :address, :zip )
joe = customer.new( "JoeSmith", "123 Maple, Anytown NC", 12345 )
MyRuby::cFunction(joe)

cFunction() で構造体メンバー (名前、アドレスなど) を取得する方法を教えてもらえますか? 前もって感謝します

4

1 に答える 1

1

これは機能します(堅牢ではありません):

puts(STR2CSTR(rb_funcall(str, rb_intern("name"), 0)));
puts(STR2CSTR(rb_funcall(str, rb_intern("address"), 0)));
printf("%i\n", NUM2INT(rb_funcall(str, rb_intern("zip"), 0)));

パフォーマンスを向上させるには、C コードで構造体型を定義してから、Pickaxe の第 17 章Data_Wrap_Structで概説され ているように、それを Ruby オブジェクトに拡張する必要があります。

于 2011-09-16T11:16:46.497 に答える