2014-12-01 53 views
0

我如何爲ruby做類似的操作。我無法找到將對象轉換爲變量的示例/文檔。例如在C中擴展Ruby - 將參數轉換爲C類型

Local<Object> obj = args[0]->ToObject(); 
Local<Array> props = obj->GetPropertyNames(); 

我正在用ruby重寫節點擴展。任何形式的幫助都會非常有幫助。由於

static Handle<Value> SendEmail(const Arguments& args) 
{ 
    HandleScope scope; 

    list<string> values; 
    Local<Object> obj = args[0]->ToObject(); 
    Local<Array> props = obj->GetPropertyNames(); 

    // Iterate through args[0], adding each element to our list 
    for(unsigned int i = 0; i < props->Length(); i++) { 
     String::AsciiValue val(obj->Get(i)->ToString()); 
     values.push_front(string(*val)); 
    } 

    // Display the values in the list for debugging purposes 
    for (list<string>::iterator it = values.begin(); it != values.end(); it++) { 
     cout << *it << endl; 
    } 

    return scope.Close(args.This()); 
} 
+0

你嘗試了谷歌搜索:「類型轉換的紅寶石」。 – lurker 2014-12-01 18:11:16

+0

是的。很遺憾,無法獲得有用信息 – mandss 2014-12-01 19:52:59

+0

,因爲ruby不是強類型的,所以在ruby中沒有「類型轉換」的概念 - 它就是這樣......你可能想要_transform_和object,或者_convert_它,但是cast沒有意義 – 2014-12-02 07:27:44

回答

1

我不完全相信,我明白你的問題,因爲你標記這個問題爲C,你的代碼示例是C++,但無論哪種方式,如果你試圖延長紅寶石,您需要將ruby值轉換爲C類型,以及是否計劃使用C++數據結構,從C類型到C++對象。

使用Ruby的C API:

#include "ruby.h" 
//Define module my_module (this can be any name but it should be the name of your extension 
VALUE MyModule = Qnil; 
//Initialization prototype - required by ruby 
void Init_MyModule(); 
//method prototype declarations - all methods must be prefaced by method_ 
VALUE method_get_some_ruby_value(); 

//actual method 
VALUE get_some_ruby_value(VALUE self, VALUE some_value) 
{ 
    //If your value is a ruby string - the StringValue function from ruby will ensure 
    //that you get a string no matter what, even if the type being passed is not a string. 
    VALUE r_string_value = StringValue(some_value); 

    //Now we tell the Ruby API to give us the pointer to the ruby string 
    //value and we assign that to a native char * in C. 
    char *c_string_value = RSTRING_PTR(r_string_value); 

    //Now do something with the char * - for example, turn it into a C++ string 
    std::string str(c_string_value); 
    // ...do something useful here... 

    return Qnil; // If you want to return something back to ruby, you can return a VALUE. 
} 
//Ruby calls this to initialize your module in ruby 
VALUE Init_MyModule() 
{ 
    //This defines your module in ruby 
    MyModule = rb_define_module("MyModule"); 
    //This defines the method - the module it is in, the ruby method name, the actual method ruby will call, and the number of arguments this function is expected to take 
    rb_define_method(MyModule, "get_some_ruby_value", get_some_ruby_value, 1); 
} 

如果您想了解關於通過結構來回的Ruby/C/C++之間,你需要有紅寶石的透徹瞭解和Ruby的C^API在開始嘗試使用C++對象之前。

這裏有幾個優秀的資源,讓你開始:

http://silverhammermba.github.io/emberb/c/ http://java.ociweb.com/mark/NFJS/RubyCExtensions.pdf