【问题标题】:How do I return 'nil' from a ruby C++ extension using Rice如何使用 Rice 从 ruby​​ C++ 扩展返回“nil”
【发布时间】:2014-11-24 22:10:29
【问题描述】:

我正在使用 Rice 开发一个 Ruby C++ 扩展,并且在 C++ 中有一个返回指针或 NULL 指针的 finder 方法。

Instrument* Parser::getInstrumentPtr(const long int code) {
Instrument* instru = NULL;
instrument_db::iterator instr_iter = std::find_if(instruments.begin(), instruments.end(), FindInstrument(code));
if (instr_iter != instruments.end())
    {
    instru = &(*instr_iter);
    }
    else
        std::cout << "Not found C++" << std::endl;
return instru;
}

这个方法用ruby封装如下:

    Data_Type<Parser> rb_cParser =  define_class<Parser>("Parser")
                            .define_constructor(Constructor<Parser, const char*>())
                            .define_method("file=", &Parser::setFileName)
                            .define_method("file", &Parser::getFileName)
                            .define_method("instruments", &Parser::getInstruments)
                            .define_method("find_instrument", &Parser::getInstrumentPtr)
                            .define_method("find_instrument_by_composite_code", &Parser::getInstrumentByCompositeCode);

我希望 ruby​​ 方法 find_instrument 返回 nil,以防找不到仪器。 到目前为止,我在 ruby​​ 中获得了 Instrument 对象:

instr_parser.instruments.each do | instr|
  instr_ref = parser.find_instrument(instr.code)
  pp instr_ref 
  if !instr_ref.nil?
    #puts "Found instrument #{instr_ref.code}"
    puts "Reference is instrument #{instr.code}"
  else
    puts "Not found" 
  end
end
======> OUTPUT ======>
#<Instrument:0x000000087a1ab8>
Reference is instrument -1
Not found C++
#<Instrument:0x000000087a1158>
Reference is instrument -1
...

我以为 Rice 知道如何管理 NULL 指针并转换为 ruby​​ nil 对象......

  • 我是不是做错了什么(我不是 C++ 专家)?
  • 我该怎么做才能返回 nil ?

【问题讨论】:

    标签: c++ ruby null ruby-rice


    【解决方案1】:

    在 C++ 中,NULL 为 0,它不是指针,它在 cstddef #define NULL 0 中定义,尝试返回 nullptr instand

    【讨论】:

      猜你喜欢
      • 2013-10-01
      • 1970-01-01
      • 2020-10-21
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-08-10
      • 2017-11-13
      • 1970-01-01
      相关资源
      最近更新 更多