Why does GLTextureBuilder.build return a Texture not a GLTexture?

GdkGLTexture.build creates and returns a GLTexture, but casts the return value to a Texture (the base class of GLTexture) before returning it. Why?

The relevant sources (gdk_gl_texture_builder_build, gdk_gl_texture_new_from_builder) show that the created object is indeed always a GLTexture; there’s no other type that it could return.

Moreover, it would be extremely surprising if it returned anything else. The name is crystal clear: it’s a GLTexture builder.

The MR (Add GdkGLTextureBuilder (!5862) · Merge requests · GNOME / gtk · GitLab) has no discussion of this point. Why needlessly compromise on type-safety in this way; is it intentional?

Which programming language are you using?

In the C API, it’s common for GTK to return base classes as that avoids additional casts when using the returned instance; there are more consumers of GdkTexture than GdkGLTexture.

You can see this pattern in play in most of the GTK widget API, where constructors return GtkWidget instead of the constructor’s type.

This is less of an issue on higher level languages.

Thanks @ebassi for the quick reply as always.

I’m programming in C++. The glibmm wrapper doesn’t translate the return type to GLTexture, unlike most other constructors, and this seems like an oversight - probably now frozen in due to ABI.

Still, there’s nothing to stop the docs calling it a GLTexture. But they also refer to it as Texture, in contrast to other widget constructors:

Description: Builds a new GdkTexture with the values set up in the builder.
Return value: A newly built GdkTexture

So you can see how this can lead to the confusion.

gtkmm usually use the data types corresponding to the types used in gtk.
For instance when gdk_gl_texture_builder_build() returns GdkTexture*,
Gdk::GLTextureBuilder::build() returns Glib::RefPtr<Gdk::Texture>.

Provided the returned object is really a GdkGLTexture, it will be wrapped in a
Gdk::GLTexture object. You can dynamic-cast it, if you want to use GLTexture API.

auto texture = my_gl_texture_builder->build();
auto gl_texture = std::dynamic_pointer_cast<Gdk::GLTexture>(texture);
if (gl_texture) // If you want to be extra safe.
  // Your code here

@kjellahl I see you’ve already pre-empted my possible bug report :smiley:

I can also static_pointer_cast it if I’m feeling really sure about the type.

gtkmm usually use the data types corresponding to the types used in gtk.

But not for constructors, for example

GtkEventController *gtk_event_controller_motion_new();
Glib::RefPtr<EventControllerMotion> EventControllerMotion::create();

GLTextureBuilder.build is really a constructor - it replaced the now-deprecated one for GLTexture.

This topic was automatically closed 30 days after the last reply. New replies are no longer allowed.