With g_signal connect, I'm trying to pass a parameter that is a simple character 'S' using the "data" field.

???(I think I understand that the field is not for data, rather its for a pointer to the data.)???

Anyway, I have code like this:

g_signal_connect (G_OBJECT(b_save), "clicked", my_test, (gpointer) 'S'); 

calling code like this:

void my_test(GtkMenuItem *menuitem, gpointer data) { printf("Pointer variable contains: %p\n", data); } 

I'm not sure if my_test should accept two parameters or one? I'm not sure how to printf the pointed to value 'S'. (In my called function my_test how do I get at the 'S'?)

1 Answer

'S' is a character constant. Unlike string literals, character constants aren't addressable, they are just a number in disguise. So the data parameter in your callback doesn't contain a pointer to 'S' (no more than it could contain a pointer to the constant 1), but instead is the value of the constant reinterpreted as a gpointer.

If your C implementation guarantees the 1-to-1 mapping between integers and pointers, you can keep your setup, and have your callback print like this:

printf("Data variable contains: %c\n", (char)data); // char and NOT char* 

If you want to pass addresses, then you need to pass the address of some storage. More importantly, storage that won't expire before the callback is executed. Dynamically allocating the memory is probably best, but you can pass the address of a static variable as well:

static char data = 'S'; g_signal_connect (G_OBJECT(b_save), "clicked", my_test, &data); // ... printf("Data variable contains: %c\n", *(char*)data); // Now data is a pointer to a single character. 
6

Your Answer

Sign up or log in

Sign up using Google Sign up using Facebook Sign up using Email and Password

Post as a guest

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.