0

I am trying to create a python binding of a virtual class with pybind. I've been following pybind11 documentation and this is what I have

TestField.h

class AbstractTestField
{
public:
    virtual ~AbstractTestField() = default;

    virtual double test() const = 0;
};

class TestField : public AbstractTestField
{
public:
    ~TestField() = default;

    double test() const final;
};
}  // namespace VNCS

TestField.cpp

double VNCS::TestField::test() const
{
    PYBIND11_OVERLOAD_PURE(double,          /* Return type */
                           VNCS::TestField, /* Parent class */
                           test             /* Name of function in C++ (must match Python name) */
    );
}

bindings.cpp

#include <pybind11/pybind11.h>
#include "TestField.h"

namespace py = pybind11;

PYBIND11_MODULE(VNCSSofaPlugin, m)
{
    m.doc() = "Test bindings";
    m.attr("__version__") = "dev";

    py::class_<AbstractTestField, TestField>(m, "TestField")
        .def(py::init<>())
        .def("test", &AbstractTestField::test);
}

I am using CMake as my build system, and I create two targets. One for the C++ code and one for the bindings.

For the C++ one I have something like this

set(SOURCES TestField.cpp)
set(PUBLIC_HEADERS TestField.h)
add_library(VNCSSofaPlugin SHARED ${SOURCES} ${HEADERS})
...

and for the bindings I have this

set(SOURCES bindings.cpp)
pybind11_add_module(VNCSSofaPluginBinding ${SOURCES})

target_link_libraries(VNCSSofaPluginBinding PUBLIC VNCSSofaPlugin)

This compiles fine and it generates two libraries: libVNCSSofaPlugin.so and VNCSSofaPluginBinding.cpython-38-x86_64-linux-gnu.so

However, when I try to import the binding in python, I get the following issue

Python 3.8.6 (default, Sep 30 2020, 04:00:38)
[GCC 10.2.0] on linux
Type "help", "copyright", "credits" or "license" for more information.
>>> import VNCSSofaPluginBinding
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
ImportError: /mnt/D/jjcasmar/projects/VNCSSofaPlugin/build/Debug/lib/VNCSSofaPluginBinding.cpython-38-x86_64-linux-gnu.so: undefined symbol: _ZTIN4VNCS9TestFieldE

I dont understand why is not being able to find the constructor. What am I doing wrong?

jjcasmar
  • 1,387
  • 1
  • 18
  • 30
  • `_ZTIN4VNCS9TestFieldE` isn't the destructor it [demangles](https://demangler.com/) to `typeinfo for VNCS::TestField`, generally it can be fixed by defining at least 1 virtual method (e.g. the destructor) in a cpp file. – Alan Birtles Oct 16 '20 at 19:06
  • I have defined in the cpp file both the AbstractTestField dtor and the TestField dtor. However, now it complainst about `_ZTIN4VNCS17AbstractTestFieldE` – jjcasmar Oct 16 '20 at 19:22
  • please provide a [mre] – Alan Birtles Oct 16 '20 at 20:32
  • Actually I have been able to solved it. I have moved the implementation of the abstract class into the target creating the bindings and that solved the issue. – jjcasmar Oct 16 '20 at 20:50

0 Answers0