简体   繁体   中英

How do I return 'nil' from a ruby C++ extension using Rice

I am developping a Ruby C++ extension using Rice, and have a finder method in C++ that either returns a pointer or NULL pointer.

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;
}

This method is wrapped in ruby as follows:

    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);

I want the ruby method find_instrument to return nil in case the instrument is not found. So far I am getting in ruby an Instrument object :

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
...

I thought Rice knew how to manage NULL pointers and do the conversion to a ruby nil object...

  • Did I do something wrong (I am no C++ expert) ?
  • What can I do to return nil ?

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM