[C++-sig] Fwd: Wrapping a singleton using pybind11?

Skip Montanaro skip.montanaro at gmail.com
Mon Jan 23 15:47:56 EST 2017


Looking around for help with pybind11, I saw a brief flurry of
activity related to it here back in Oct 2015, when Wenzel Jakob
introduced it. Since then, not so much.

I'm trying to come up-to-speed with it, though I'm not a C++
programmer, so it's been a slow slog so far. Almost the first thing I
tried to do has me stumped. I have a singleton class (no public
constructor, C++ programmers call an instance() member function). As a
Python programmer, that seems crude to me. In Python, I'd write a
__new__ method and let programmers pretend they have different
instances.

We already have some Boost.Python wrappers for parts of our C++
libraries. The general strategy there seems to be to create a second
struct which does have a constructor and a bunch of one-line member
functions, then use

  .def(py::init<>())

That also seems crude, *and* makes me have to repeat myself. For every
member function (static or otherwise) that I want to expose, not only
do I have to add the necessary .def(...) call, I have to also add a
silly member function to that artificial struct created to provide a
public constructor. (And since they are structurally separate, I can't
even use preprocessor macros to expand things.)

Is there an straightforward way to wrap a singleton class using
pybind11 which minimizes the amount of boilerplate I have to write? I
thought I'd be able to figure out type converters, then write a few
.def(...) calls, and be done with it. That's turning out not to be the
case, at least not for me. I suppose if was an actual C++ programmer,
I would be further along at this point.

Thanks,

Skip Montanaro


More information about the Cplusplus-sig mailing list