[C++-sig] Using boost for both embedding and extending.

Kirsebom Nikolai nikolai.kirsebom at siemens.no
Mon May 26 09:58:33 CEST 2003


Hi,
I'm trying to embed Python (2.2.2 later 2.3) in our application (MFC based,
VS 6.0, Windows 2000) and at the same time expose some of the applications
objects (datamodel), using Boost(v2).  If I run the code given below, it
'core dumps' due to the line "ab = v.GetMenuEntry()\n" in the first
PyRun_String statement.  Leaving out this python-statement, I'm able to (as
an example) extract the number for "e" as shown in the second PyRun_String
statement.

Quite sure it is an easy issue, however I've tried to copy the example of
'singleton' from the boost.python documentation, but obviously I must have
missed out something.

Thanks for any help.

Nikolai


--------------
#include "stdafx.h"

#include "Python.h"  //<<-- replaced when running in debug mode
#include <boost/python.hpp>

using namespace boost::python;

class DLEPRinterface {
public:
	DLEPRinterface();

	CString GetMenuEntry();
};

DLEPRinterface::DLEPRinterface()
{
}

CString DLEPRinterface::GetMenuEntry()
{
	return _T("The menu entry");
}

class Element {
public:
	Element();
	void SetNumber(int nbr);
	int GetNumber();

private:
	int m_Number;
};

Element::Element()
{
}

void Element::SetNumber(int nbr)
{
	m_Number = nbr;
}

int Element::GetNumber()
{
	return m_Number;
}

DLEPRinterface* getit() {
	static DLEPRinterface *v = NULL;
	if (DLEPRinterface == NULL) {
		v = new DLEPRinterface();
	}
	return v;
}


BOOST_PYTHON_MODULE(CppDocuLive)
{
	def("getit", getit,
return_value_policy<reference_existing_object>())
	;
	class_<DLEPRinterface>("DLEPRinterface")
		.def("GetMenuEntry", &DLEPRinterface::GetMenuEntry)
	;
	class_<Element>("Element")
		.def("SetNumber", &Element::SetNumber)
		.def("GetNumber", &Element::GetNumber)
	;
}


//TheClass
TheClass::TheClass()
{
}

TheClass::~TheClass()
{
}

CString TheClass::RunStmt()
{
	if (PyImport_AppendInittab("CppDocuLive", initCppDocuLive) == -1)
		throw std::runtime_error("Failed to add CppDocuLive to the
interpreter's builtin modules");
	
	Py_Initialize();

	handle<> main_module(borrowed( PyImport_AddModule("__main__")));
	handle<> main_namespace(borrowed(PyModule_GetDict(main_module.get())
));
	
	handle<> result(PyRun_String(
		"import CppDocuLive\n"
		"v = CppDocuLive.getit()\n"
		"ab = v.GetMenuEntry()\n"
		"e = CppDocuLive.Element()\n"
		"e.SetNumber(345)\n",
		Py_file_input, main_namespace.get(),main_namespace.get()));
	result.reset();

	PyObject *p = PyRun_String("e.GetNumber()",
Py_eval_input,main_namespace.get(), main_namespace.get());
	/* 
	.
	.
	.
	.
	*/    
    
    	Py_Finalize();

}
-----------------




More information about the Cplusplus-sig mailing list