How to send data into function after button click (e.g. vector) - gtk4 C/C++

,

Hello all,
please I need again some help in gtk4 C/C++ app
I need to send to function after button click some data (e.g. vector of string) into function.

I did it similarly in gtk2

But when function CallFunct is called it crash with :

CallFunct - start 
terminate called after throwing an instance of 'std::bad_array_new_length'
  what():  std::bad_array_new_length

please could any body advice me - what is wrong in my code:

#include <gtk/gtk.h>
#include <iostream>
#include <stdio.h>
#include <stdlib.h>
#include <string>
#include <vector>

using namespace std;

void VypisVektorStringu (vector<string> vektor)
{
    unsigned int vSize = vektor.size();
    cout << "Size of vector: " << vSize << endl;

    for (unsigned int i = 0; i<vSize; ++i)
    {
        cout << vektor.at(i)<<endl;
    }
}

static void CallFunct (GtkWidget *wid, GtkWidget *data)
{
    cout << "CallFunct - start " << endl;
    vector <string>* vNew = reinterpret_cast<vector <string>*>(g_object_get_data(G_OBJECT(data), "vect"));
    VypisVektorStringu(*vNew);
}

static void appActivate (GApplication *app, gpointer user_data)
{
    vector <string> vect;
    vect.push_back("text1");
    vect.push_back("text2");
    vect.push_back("text3");
    vect.push_back("text4");

    //VypisVektorStringu(vect);

    vector <string>* vectPtr = &vect; // to test if I work with pointer well
    VypisVektorStringu(*vectPtr);

    GtkWidget *win = gtk_application_window_new (GTK_APPLICATION (app));
    gtk_window_set_title (GTK_WINDOW (win), "Your app");

    GtkWidget  *vBox = gtk_box_new (GTK_ORIENTATION_VERTICAL,10);

    gtk_window_set_child (GTK_WINDOW (win), vBox);

    GtkWidget *btn = gtk_button_new_with_label("btn");
    gtk_box_append (GTK_BOX (vBox), btn);

    GtkWidget *btnBack = gtk_button_new_with_label("Close");

    g_object_set_data(G_OBJECT(btn), "vect", &vect);
    g_signal_connect (G_OBJECT(btn), "clicked", G_CALLBACK (CallFunct), btn);

    gtk_widget_show (win);
}


int main(int argc, char **argv)
{
    GtkApplication *app;
    app = gtk_application_new ("testing.app", G_APPLICATION_FLAGS_NONE);
    g_signal_connect (app, "activate", G_CALLBACK (appActivate), NULL);
    return g_application_run (G_APPLICATION (app), NULL, NULL);
    g_object_unref (app);

    return 0;
}

thanks a lot

That has nothing to do with gtk4, more with stack allocated data, scopes, lifetimes of C++ objects and, frankly, basics of C(++) programming.

More specifically: You save a pointer to vector<string> vect, which is allocated
on the stack in the appActivate() signal handler. You try to use that vector
in the CallFunct() signal handler. appActivate() has finished long before
CallFunct() is called. The vector does no longer exist when you try to access it.

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