I'm currently working on a library, and ran into some strange inconsistencies in behaviour between my unit test code, and an actual app I'm basing on the code.
See, I'm trying to get a Type
struct from the name of the class I want to instantiate, but I get nothing (e.g. Type is there, but name()
produces null
, is_a()
fails, etc.)
However, if I make an instance of the type first, then try to get the Type based on name once more, it works just as I expected (which is probably why my unit tests work)
So I was wondering, when is a type registered by the type system and available via. from_name(...)
?
Does the type system only know it after it has been instantiated at run time? Is there another reason a class name wouldn't be recognized until an instance of the class has been instantiated? Should I use some other method of registration?
I'm coding in Vala if that makes any kind of a difference.
A type is first registered with the type system when its get_type()
function is called. This is called in a number of places, basically whenever you need to get the GType
for that type. Typically, it will first be called during class_init
of the type, which happens during the first instance init
.
So essentially you are right when you say “does the type system only know it after it has been instantiated at run time”, because that’s normally what happens. However, you can bring type registration forward by explicitly calling the get_type()
function for a type early, and passing it to g_type_ensure()
. For example, see what GLib does here:
/* Initialize types from built-in "modules" */
g_type_ensure (g_null_settings_backend_get_type ());
g_type_ensure (g_memory_settings_backend_get_type ());
g_type_ensure (g_keyfile_settings_backend_get_type ());
…