Re: Is there any problem to create C++ classes from C (Gtk::Window, etc) ?
- From: Chris Vine <chris cvine freeserve co uk>
- To: Germán Diago <germandiago gmail com>
- Cc: gtkmm-list gnome org
- Subject: Re: Is there any problem to create C++ classes from C (Gtk::Window, etc) ?
- Date: Sat, 7 Nov 2009 17:02:56 +0000
On Sat, 7 Nov 2009 14:16:18 +0100
Germán Diago <germandiago gmail com> wrote:
>
> Hello. I have a very technical issue. If some expert could tell me if
> it's wrong.
> The issue is that I can do this:
>
>
> GObject * obj = G_OBJECT(g_type_new("MycppClass", NULL));
>
> as long as MyCppClass has this layout:
>
> class .... {
> GObject parentclass;
> ...
> };
>
> If I define a virtual function, it won't work anymore. Is there any
> workaround to this?
> Because in the c gobject manual it says that the layout must be like
> that, in order
> for GObject to work, but for C++ it's very inflexible.
>
> Is there any well-known solution to workaround the virtual table issue
> and keep my classes
> working in C? Thanks.
I am not entirely sure what you are trying to do, but if your
MyCppClass is a POD (in particular, it has no virtual functions) then
you can derive from that with a child class with virtual functions.
Note however that you must use a static_cast to go from MyCppClass to
its child and not a reinterpret_cast, because they will likely have
different addresses because of the child's vtable. static_cast will
automatically provide an address offset when casting (it is required to
do so by the standard) and reinterpret_cast will not.
In other words, you could have MyVirtualClass as a child of MyCppClass,
and do a reinterpret_cast from the GObject parentclass to MyCppClass
(if MyCppClass is a POD), and then a static_cast to MyVirtualClass. As I
say, though, I do not know if that is in fact the kind of thing you are
after. As I also say, the point to always be aware of is that
reinterpret_cast<void*>(my_virtual_class) and
reinterpret_cast<void*>(static_cast<MyCppClass*>(my_virtual_class))
are likely to yield different values - you can test it with a std::cout
if you are interested. Whethere it does or not depends on where the
compiler puts the vtable.
Chris
[
Date Prev][
Date Next] [
Thread Prev][
Thread Next]
[
Thread Index]
[
Date Index]
[
Author Index]