I'm writing some GObject code, and so far all my types have implemented an interface but been final types. Now I'm trying to make a new type that implements the same interface but also is a derivable type, however I'm not sure how. Previously I've used G_DEFINE_TYPE_WITH_CODE
to define types that implement my interface, but I need a private struct to store instance variables, and for that the G_DECLARE_DERIVABLE_TYPE
docs say to use G_DEFINE_TYPE_WITH_PRIVATE
. It is not obvious to me how these would be combined, and I haven't been able to find any explanation in the documentation. I tried using both, but understandably it gives me errors about redefinitions.
How do I go about defining a derivable type that also implements an interface and has a private struct in GObject C?
I need a private struct to store instance variables, and for that the
G_DECLARE_DERIVABLE_TYPE
docs say to useG_DEFINE_TYPE_WITH_PRIVATE
No, not exactly. The docs provide an example that uses G_DEFINE_TYPE_WITH_PRIVATE
, but that doesn't mean that that macro itself is required. That example is prefaced with
Since the instance structure is public it is often needed to declare a private struct
, and you should understand that the use of G_DEFINE_TYPE_WITH_PRIVATE
is primarily to be contrasted with using (only) G_DEFINE_TYPE
, as the latter does not provide a private struct.
You write:
Previously I've used
G_DEFINE_TYPE_WITH_CODE
to define types that implement my interface
All of the G_DEFINE_TYPE*
macros are based on G_DEFINE_TYPE_EXTENDED
. The others provide specialized front ends to this macro, with various subsets of the arguments. If you want to define a type with both code and private data then you can do this via G_DEFINE_TYPE_EXTENDED
. Do read its docs.
However, you probably don't need to go that far. I think you should be able to use G_ADD_PRIVATE
in the code section of G_DEFINE_TYPE_WITH_CODE
(probably along with other things) to get private data into your type.
Since this is indeed a bit opaque, it would probably be worthwhile to compare the code generated by various options and combinations. You can do this by running the preprocessor on your code, and then (strongly recommended) passing it through a code formatter.