Unsure about the concept of using function macros as entry point to C++ program,

Viewed 216

I'm totally lost about the concept of using function macros as entry point to C++ program, especially with reference to the sample C++ code as listed below.

The website where the sample code was found (https://docs.microsoft.com/en-us/visualstudio/python/working-with-c-cpp-python-in-visual-studio?view=vs-2019#convert-the-c-projects-to-extensions-for-python), says: 1) the following code creates a macro called PYBIND11_MODULE 2) it establish it as entry point. I couldn't make any sense of this statement as I think:1) a macro needs to be defined using "#DEFINE" pre-compile directive. In the following sample code, PYBIND11_MODULE{} doesn't have "#DEFINE". 2) I can't figure out where an entry point get established. I only know by the way C++ is created, "main" is the default entry point.

Thank you very much!

namespace py = pybind11;

PYBIND11_MODULE(superfastcode2, m) {
    m.def("fast_tanh2", &tanh_impl, R"pbdoc(
        Compute a hyperbolic tangent of a single argument expressed in radians.
    )pbdoc");

#ifdef VERSION_INFO
    m.attr("__version__") = VERSION_INFO;
#else
    m.attr("__version__") = "dev";
#endif
}
1 Answers

The macro defines a function as the entry point for a Python module, not for a C program.

CPython extensions are DLLs, so no main, just functions.


PYBIND11_MODULE(superfastcode2, m) {
    m.def("fast_tanh2", &tanh_impl, R"pbdoc(
        Compute a hyperbolic tangent of a single argument expressed in radians.
    )pbdoc");
}

The docs says:

The PYBIND11_MODULE() macro creates a function that will be called when an import statement is issued from within Python. The module name (example) is given as the first macro argument (it should not be in quotes). The second argument (m) defines a variable of type py::module which is the main interface for creating bindings.

The macro will expand to some code that will ultimately be called by Python when the DLL is loaded.

Related