Boost::python help

Started by
1 comment, last by perfectly_dark 18 years, 8 months ago
Hello, I'm trying to use boost::python in a project but it's seems to be quite difficult. And the lack of detailed documentation isn't helpful, I spent last night figuring out that I have to compile Boost::python first. Anyways, now it seems to be compiling some functions I'm exposing to python. But I don't want to make a python module or bother with bjam. All I want is to embed the python interpreter in my app and use scripts to call C++ functions. Is this even possible? I'm working with this: http://www.boost.org/libs/python/doc/index.html but it doesn't seem to be covered. Does anyone have any source code that does this? Here's what I've got but it doesn't actually do anything (probably cause I'm an idiot :P):
#include <iostream>
#include <boost/python.hpp>
#include <python.h>

using namespace boost::python;

char const * hello()
{
	return "hello dude";
}

BOOST_PYTHON_MODULE(test)
{
	def("hello", hello);
}

int main()
{
	Py_Initialize();
		PyObject * pName = PyString_FromString("test");
		PyObject * pModule = PyImport_Import( pName );
		if(! pModule )
		{
			std::cout << "Failed to load script" << std::endl;
		}
	Py_Finalize();

	return 0;
}
and test.py:

import test
test.hello()
Any help or insight would be greatly appreciated. And sorry if anything I ask is stupid, this is my first foray into scripting. Thanks!
Advertisement
This is probably a good sign that I need to finish my article on embedding Python. Anyways, in order to actually expose your module to the Python interpreter you need to call the init function. boost::python calls it init(your_module_name), so in your case it looks like inittest(). Just call it after your Py_Initialize() call. (I give my Python modules capitalized names so it doesn't look so funky, like module Test would become initTest()). I would also test the module first with PyRun_String() before you try loading a script from the disk.

Oh and calling the module that you expose the same name as the script you are trying to load is probably not a happy thing either.
Thanks SiCrane! You're the champ!
PS I'll be waiting for that article :P

This topic is closed to new replies.

Advertisement