0
非常に簡単なアプリケーション - コピー&ペーストを実行できます。 メインでは単にアプリケーションを作成しています。 - それは期待通り(一部の住所と変数の正しい値)に「test_fce」機能の3倍の出力を印刷する - ここでの問題(おそらく)コールバック関数の値が異なる - 悪いのはなぜですか?
#include <stdlib.h>
#include <stdio.h>
#include <string.h>
#include <gtk\gtk.h>
typedef struct{
int a;
int *p;
}struct_int;
static void test_fce(gpointer data){
struct_int *local = (struct_int *)data;
printf("\n");
printf("local %p\n", local);
printf("local a %i\n", local->a);
printf("local &a %p\n", &(local->a));
(local->a)++;
printf("local p %p\n", local->p);
printf("local &p %p\n", &(local->p));
printf("local *p %i\n", *(local->p));
(*(local->p))++;
}
static void write_value(GtkButton *button,
gpointer data)
{
struct_int *local = (struct_int *)data;
printf("\n");
printf("local %p\n",local);
printf("local a %i\n", local->a);
printf("local &a %p\n", &(local->a));
printf("local p %p\n", local->p);
printf("local &p %p\n", &(local->p));
printf("local *p %i\n", *(local->p));
}
static void activate (GtkApplication* app,
gpointer user_data)
{
int i = 7;
GtkWidget *main_window, *button;
struct_int test_struct;
main_window = gtk_application_window_new (app);
button = gtk_button_new_with_label ("Start");
gtk_container_add (GTK_CONTAINER (main_window), button);
gtk_widget_show_all (main_window);
test_struct.a = 5;
test_struct.p = &i;
printf("i %i\n",i);
printf("&i %p\n",&i);
printf("test_struct_p& %p\n", &test_struct);
printf("test_struct_p a %i\n", test_struct.a);
printf("test_struct_p &a %p\n", &(test_struct.a));
printf("test_struct_p p %p\n", test_struct.p);
printf("test_struct_p &p %p\n", &(test_struct.p));
printf("test_struct_p *p %i\n", *(test_struct.p));
test_fce((gpointer) &test_struct);
test_fce((gpointer) &test_struct);
g_signal_connect (G_OBJECT(button), "clicked", G_CALLBACK (write_value), (gpointer) &test_struct);
test_fce((gpointer) &test_struct);
}
int main (int argc,
char **argv)
{
GtkApplication *app;
int status;
gtk_init(&argc, &argv);
app = gtk_application_new ("a.b.my_app", G_APPLICATION_FLAGS_NONE);
g_signal_connect (app, "activate", G_CALLBACK (activate), NULL);
status = g_application_run (G_APPLICATION (app), argc, argv);
g_object_unref (app);
return status;
}
は、私がアプリケーションを実行する場合ではありません。
しかし、私はボタンをクリックしたとき、すべての印刷されたアドレスは、(test_fceと同じ)corectですが(「」「P」の 値が悪い、(常に0であるように思わ)悪いの 値がいるようですいつも000000 ...) 私は "* p"プログラムへのアクセスを試みる行が落ちる。
コードに問題がありますか?
編集:それを修正するための「最良の」方法は何ですか?
速い応答のために:-)私は主な質問を編集していますが、それを修正する最良の方法は何ですか?私はgtkの公式サイトの例からこの構造を取ったので、絶対に使えないわけではないと思います... –
'test_struct'を' g_malloc() 'を使ってヒープ上に割り当てる必要があります(変数はポインタでなければなりません'&test_struct'を' g_signal_connect() 'に渡さないようにします)。 'g_free()'が不要になったときには、 'activate()'ではなく、 'g_free()'を呼び出すのはあなた次第です。 – andlabs
はい、 'test_struct'と' i'は、関数が返った後にアクセスされている 'activate'関数の自動ストレージクラス変数です。 (ボタンをクリックすると 'write_value'関数によってアクセスされます) –