I have to expose a C++ enum class into python.
I have checked some examples but all are about C-style enum
type. However, I need to use enum
class. Any suggestion?
Here is my code:
zoo.h
namespace extzoo
{
namespace intzoo
{
class zoo
{
public:
enum class Size
{
small, medium, large
};
const std::string hello_zoo();
const std::string getname_zoo();
const Size get_size();
void set_size(Size);
private:
Size size;
};
}
}
zoo.cpp
using namespace extzoo::intzoo;
using namespace extzoo;
const std::string zoo::hello_zoo() {
return std::string("hello, zoo");
}
const std::string zoo::getname_zoo() {
std::string input;
std::cout<<"Please enter your favorit zoo name: ";
std::getline(std::cin,input);
return std::string("Your favorit zoo name is: ").append(input);
}
const zoo::Size zoo::get_size()
{
return this->size;
}
void zoo::set_size(zoo::Size s)
{
this->size = s;
}
My code to expose C++ methods to python
pyintf.cpp
class DummyZoo{
};
BOOST_PYTHON_MODULE(pyintf) {
extzoo::intzoo::
python::enum_<zoo::Size>("Size")
.value("small", zoo::small)
.value("medium", zoo::medium)
.value("large", zoo::large)
;
scope intzoo
= class_<DummyZoo>("intzoo");
class_<intzoo::zoo>("zoo")
.def("hello_zoo", &extzoo::intzoo::zoo::hello_zoo)
.def("getname_zoo", &extzoo::intzoo::zoo::getname_zoo)
.def("get_size",&extzoo::intzoo::zoo::get_size)
.def("set_size",&extzoo::intzoo::zoo::set_size)
;
}
I got the following errors:
[root@localhost enumclass]# g++ -shared -std=c++11 -o pyintf.so -fPIC pyintf.cpp zoo.h zoo.cpp -lboost_python -lpython2.7 -I/usr/include/python2.7
pyintf.cpp: In function ‘void init_module_pyintf()’:
pyintf.cpp:34:2: error: ‘extzoo::intzoo::python’ has not been declared
python::enum_<zoo::Size>("Size")
pyintf.cpp:34:25: error: expected primary-expression before ‘>’ token
python::enum_<zoo::Size>("Size")
pyintf.cpp:35:8: error: request for member ‘value’ in ‘("Size")’, which is of non-class type ‘const char [5]’
.value("small", zoo::small)
pyintf.cpp:35:23: error: ‘small’ is not a member of ‘extzoo::intzoo::zoo’
.value("small", zoo::small)
pyintf.cpp:36:24: error: ‘medium’ is not a member of ‘extzoo::intzoo::zoo’
.value("medium", zoo::medium)
pyintf.cpp:37:19: error: ‘large’ is not a member of ‘extzoo::intzoo::zoo’
.value("large", zoo::large)
Same like in your previous SO question, the problem is that the class methods definitions aren't defined inside the namespaces. Using using namespace ...
is to bring the visibility of the content of that namespace but not for the matter of defining the content of that namespace.