Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Boost Python : Having problems importing a module

I'm currently trying to use Boost Python to export a class, and then use it in the corresponding the program.

/**
    main.cpp
*/
#define BOOST_PYTHON_STATIC_LIB
#include <Resource\ZipResourceFile.hpp>
#include <Resource\ResourceCache.hpp>
#include <Windows.h>
#include <boost/python.hpp>
#include <iostream>

/* a simple add method, for s & g's */
int add(int a, int b)
{
    return a + b;
}

/* Foo class*/
class Foo
{
public:
    Foo(int n);
    ~Foo();
    void f();
};

/* Foo ctor, does nothingm just wanted to pass and arg */
Foo::Foo(int n)
{

}

/* destructor */
Foo::~Foo()
{
}

/* f() implementation, calls Foo!!! to cout */
void Foo::f()
{
    std::cout << "Foo!!!" << '\n';
}

/* Boost python module definition */
BOOST_PYTHON_MODULE(PyBackend)
{
    using namespace boost::python;

    def("add", add);
    class_<Foo>("Foo", init<int>())
        .def("f", &Foo::f);
}



int main(int argc, char* argv[])
{
    PyImport_AppendInittab("PyBackend", init_PyBackend);
    Py_Initialize();
    PyRun_SimpleString("import PyBackend");
    PyRun_SimpleString("foo = PyBackend.Foo(1)");

    Py_Finalize();

    {
        int n;
        std::cin >> n;
    }
    return 0;
}

Anyhow, I have no idea where i can find the function init_PyBackend, even though that seems the logical thing I would call if I wasn't using Boost.Python.

The module itself isn't in a seperate DLL, it's compiled all at the same time. Anyway, anyone have any ideas on what I can do?

like image 299
DubyaDubyaDubyaDot Avatar asked May 04 '12 02:05

DubyaDubyaDubyaDot


1 Answers

The convention for naming the module initialization function is:

  • init*** for Python 2.x (no underscore).
  • PyInit_*** for Python 3.x.

Boost.Python's BOOST_PYTHON_MODULE macro follows these conventions.

Since you're using Python 3.2, the initialization function of your PyBackend module will therefore be called:

PyInit_PyBackend.

Note that for modules with names starting with an underscore, like _sre, the init functions are init_sre/PyInit__sre (notice two underscores for Python 3.x).

like image 94
yak Avatar answered Sep 19 '22 23:09

yak