[C++-sig] Calling Object virtual function from C++

William Marié william.marie at gmail.com
Fri Sep 5 16:01:21 CEST 2008


Hi,

I'm trying to call a object virtual function from the C++ side but if the
python function is not defined into the Python class it doesn't find the one
defined in the C++ object :

------- C++
class Base
{
public:
	Base() {};
	virtual ~Base() {};
	virtual void testVirtual()
	{ 
		itn a = 0;
	}
};

struct BaseWrap : Base, bp::wrapper<Base>
{
	void testVirtual()
	{
		if (bp::override fun = this->get_override("testVirtual"))
			fun(); // *note*
		Base::testVirtual();
	}
	void default_testVirtual() { this->Base::testVirtual(); }
};

BOOST_PYTHON_MODULE(MyModule)
{
	bp::class_<BaseWrap, boost::noncopyable>("Base")
		.def("testVirtual", &Base::testVirtual, &BaseWrap::default_testVirtual)
		;

	bp::class_<Base>("Base", bp::init<>())
		;
} 
------- Python ( testvirtual.py )
import MyModule

class TestVirtual( MyModule.Base ):

	## Constructor
	def __init__( self ) :
                pass

------------ Now from a C++ side :
bp::object module = bp::import("testvirtual");
bp::object modDict(module.attr("__dict__"));
bp::object bpClass = modDict["TestVirtual"];
bp::object bpTestVirtual = pbClass();

# Doesn't call the Base class virtual function and tell that the testVirtual
function doesn't exist
bp::object bpFun = bpTestVirtual.attr( "testVirtual" );
bpFun(); 

# Doesn't call the Base class virtual function and tell that the testVirtual
function doesn't exist bp::call<void>(bpFun.ptr());

# Doesn't call the Base class virtual function and tell that the testVirtual
function doesn't exist
bp::call_method<void>(bpTestVirtual.ptr(), "testVirtual" );

# Always call the Base::testVirtual even if the function is overidden in
Python
Base& pTestVirtual = BP_EXTRACT( bpTestVirtual, Base& );
pTestVirtual->testVirtual()


Here we go, so i'm sure there is an easy way to do that but i don't
understand what i'm doing wrong.
Could someone help me please ?
Thanks

William


-- 
View this message in context: http://www.nabble.com/Calling-Object-virtual-function-from-C%2B%2B-tp19331891p19331891.html
Sent from the Python - c++-sig mailing list archive at Nabble.com.




More information about the Cplusplus-sig mailing list