[C++-sig] virtual functions and bind size reduction

Renato Araujo renatox at gmail.com
Fri Jan 30 21:52:40 CET 2009


Hi guys,

Now I'm trying to reduce my python module.

To cut the size I've reduced the number of times that I have to expose
a function.

I had some success while working in the same module, but when dealing
with more than one things get complicated.

To do this I created a "workaround", described below (very ugly I know
but with this I save 6MB, 30%).
The problem is that between modules this does not work, there is
something wrong
during dynamic_cast calls.
I will show the basic idea of my solution. (you can check the full
code attached)

The main idea is:

I have my base and derived class like this:
===========================================
class Base {
    protected:
        virtual void virtual_func() {/*...*/}.
};

class Derived : public Base {
};


I created a proxy class:
==============================================

class BaseProxy
{
    public:
        virtual void virtual_func_proxy() = 0;
};


Now the wrapper class which inherits from my proxy class.
=========================================================

Class BaseWrapper : public Base, public wrapper<Base>, public BaseProxy
{
    public:
        void virtual_func()
        {
        }

        void virtual_func_proxy() {
            Base::virtual_func_proxy();
        }
};

Class DerivedWrapper : public Derived, public wrapper<Derived>, public BaseProxy
{
    public:
        void virtual_func_proxy() {
            Base::virtual_func_proxy();
        }
};

Then I create a function which accept my Base class.
====================================================
static void base_virtual_func(Base &self)
{
    //here is the problem this dynamic_cast fails when called from
another module
    BaseProxy *proxy = dynamic_cast<BaseProxy*>(&self);
    assert(proxy);
    proxy->virtual_func_proxy();
}

Now I export my module
=======================
//...
    class_<BaseWrap, boost::noncopyable>("Base")
        //with this not is necessary export this function again in derived class
        .def("virtual_func", base_virtual_func);

    class_<DerivedWrapper, boost::noncopyable>("Derived");
//...


This apparently works fine when running in same module but if I create a class
derived from Base in another module (another library), this stop
working because the dynamic_cast fails.

I'm not sure if this will works in all cases, but this is working fine in my
tests when in the same module.
I'll appreciate if someone give some idea how solve this, or a another
way to save
some calls of ".def" functions.

-- 
Renato Araujo Oliveira Filho
-------------- next part --------------
A non-text attachment was scrubbed...
Name: testboost.tar
Type: application/x-tar
Size: 10240 bytes
Desc: not available
URL: <http://mail.python.org/pipermail/cplusplus-sig/attachments/20090130/4bf87c32/attachment.tar>


More information about the Cplusplus-sig mailing list