Ruby/C++ integration with SWIG: problem with namespaces

Hi everyone,

I’m trying to import a C++ library in Ruby using SWIG, but I have a
problem with namespaces and enumerators: I have a namespace “mymodule”
with a function “myfunction” which takes an element of type “myenum” as
an argument.

If I define “myfunction” and “myenum” in the same source file
“mymodule.h” everything works, but if I separate them, placing “myenum”
in “myenum.h” something odd happens: I can print the value of an element
of “myenum” via Ruby but cannot pass it as an argument to “myfunction”.

Here are the source files and the error I get:

##################

mymodule.h

##################

#ifndef MYMODULE_H
#define MYMODULE_H

#include “myenum.h”

namespace mymodule {

void myfunction(myenum);

}

#endif

################

myenum.h

################

#ifndef MYENUM_H
#define MYENUM_H

namespace mymodule {

enum myenum { A, B, C };

}

#endif

####################

mymodule.cxx

####################

#include “mymodule.h”

namespace mymodule {

void myfunction(myenum c)
{
// do nothing
}

}

##################

mymodule.i

##################

%module mymodule

%{
#include “mymodule.h”
#include “myenum.h”

using namespace mymodule;
%}

%include mymodule.h
%include myenum.h

################

myapp.rb

################

require ‘mymodule’

print "I can print Mymodule::B = ", Mymodule::B, “\n”

print “but I cannot pass it as an argument:\n”

Mymodule::myfunction(Mymodule::B)

####################

command-line

####################

$ swig -c++ -ruby mymodule.i

$ g++ -fPIC -c mymodule_wrap.cxx -I/usr/lib/ruby/1.8/x86_64-linux

$ g++ -fPIC -c mymodule.cxx

$ g++ -shared -o mymodule.so *.o

$ ruby myapp.rb

I can print Mymodule::B = 1

but I cannot pass it as an argument:

myapp.rb:7:in `myfunction’: Expected argument 0 of type myenum, but got
Fixnum 1 (TypeError)
in SWIG method ‘mymodule::myfunction’ from myapp.rb:7

SOLVED

It turned out I need to write mymodule::myenum in my C++ code even if I
used the “using namespace” directive, since Swig doesn’t understand it.

This page helped me to figure this out:
http://www.geocities.com/foetsch/python/extending_python.htm

This forum is not affiliated to the Ruby language, Ruby on Rails framework, nor any Ruby applications discussed here.

| Privacy Policy | Terms of Service | Remote Ruby Jobs