I have few problems dealing with the behavior of this in vala class.
here is my code: (build_and_send1 and build_and_send2 are signals raised by pressing a button)
using GLib;
using Gtk;
public class Main : Object
{
/*
* Uncomment this line when you are done testing and building a tarball
* or installing
*/
//const string UI_FILE = Config.PACKAGE_DATA_DIR + "/" + "gtk_httpclient.ui";
const string UI_FILE = "src/gtk_httpclient.ui";
/* ANJUTA: Widgets declaration for gtk_httpclient.ui - DO NOT REMOVE */
private Builder builder;
public Main ()
{
try
{
this.builder = new Builder ();
this.builder.add_from_file (UI_FILE);
this.builder.connect_signals (this);
var window = this.builder.get_object ("window") as Window;
/* ANJUTA: Widgets initialization for gtk_httpclient.ui - DO NOT REMOVE */
window.show_all ();
stderr.printf ("constructor:\n");
stderr.printf ("this: %p\n", this);
stderr.printf ("builder: %p\n", this.builder);
}
catch (Error e) {
stderr.printf ("Could not load UI: %s\n", e.message);
}
}
[CCode (instance_pos = -1)]
public void on_destroy (Widget window)
{
Gtk.main_quit();
}
public void build_and_send1 (Widget button)
{
stderr.printf ("\nbuild_and_send1:\n");
stderr.printf ("this: %p\n", this);
stderr.printf ("builder: %p\n", this.builder);
}
[CCode (instance_pos = -1)]
public void build_and_send2 (Widget button)
{
stderr.printf ("\nbuild_and_send2:\n");
stderr.printf ("this: %p\n", this);
stderr.printf ("builder: %p\n", this.builder);
}
static int main (string[] args)
{
Gtk.init (ref args);
new Main ();
Gtk.main ();
return 0;
}
}
I've got this output :
constructor:
this: 0x1a524a0
builder: 0x1a6a230
build_and_send1:
this: 0x1aa2030
builder: 0x5a4fe823
build_and_send2:
this: 0x1a524a0
Program has been terminated receiving signal 11 (Segmentation fault)
I assume that if I want the same instance of Main in my signals, they have to be preceded by [CCode (instance_pos = -1)]. But then what is th goal of builder.connect_signals (this); ?
And why this.builder raises a segmentation fault in build_and_send2 and not in the constructor ?
Most likely, the result of new Main()
is going out of scope after construction and being garbage collected. Assign it to a variable.