c++segmentation-faultcairopangopangocairo

Segmentation fault rendering text to cairo context


It's my first time using pangomm and I am trying to render some text to a Cairo::Context, but when i try to access anything from the Pango::Layout object the program throws the following error:

(process:7175): glibmm-CRITICAL **: 15:36:58.578: Glib::ObjectBase* Glib::wrap_create_new_wrapper(GObject*): assertion 'wrap_func_table != nullptr' failed

(process:7175): glibmm-WARNING **: 15:36:58.578: Failed to wrap object of type 'PangoLayout'. Hint: this error is commonlycaused by failing to call a library init() function.
[1]    7175 segmentation fault  ./a.out

I could not backtrace the error using gdb.

Code

#include <cairomm/cairomm.h>
#include <pangomm.h>

int main() {
  auto surf = Cairo::ImageSurface::create(Cairo::Format::FORMAT_ARGB32, 1920, 20);
  auto cr = Cairo::Context::create(surf);

  cr->set_source_rgb(0.0, 0.0, 0.0);
  cr->paint();

  cr->move_to(0.0, 0.0);

  cr->set_source_rgb(1.0, 1.0, 1.0);

  auto layout = Pango::Layout::create(cr);
  auto font = Glib::ustring("Sans Bold 27");

  Pango::FontDescription desc(font);
  layout->set_font_description(desc);

  auto text = Glib::ustring("Oi");
  layout->set_text(text);

  layout->show_in_cairo_context(cr);

  surf->write_to_png("test.png");

  return 0;
}

Compiling command

g++ -g -Wall `pkg-config --cflags cairomm-1.0 pangomm-1.4` main.cpp `pkg-config --libs cairomm-1.0 pangomm-1.4`

Solution

  • Since you use pangomm without Gtk, you need to initialize pangomm at the start of your program. This also initialized Glib. Call Pango::init(); and include <pangomm/init.h>.

    Thus your code becomes

    ...
    #include <pangomm/init.h>
    
    int main()
    {
        Pango::init();
    
        ...
    }