我正在构建一个在C语言中使用GTK拖放的应用程序,但我对这部分代码有疑问
void view_onDragDataReceived(GtkWidget *wgt, GdkDragContext *context, int x, int y,GtkSelectionData *seldata, guint info, guint time,gpointer userdata)
{
GtkTreeModel *model;
GtkTreeIter iter;
model = GTK_TREE_MODEL(userdata);
gtk_list_store_append(GTK_LIST_STORE(model), &iter);
gtk_list_store_set(GTK_LIST_STORE(model), &iter, COL_URI,(gchar*)seldata->data, -1);
pathh=(char*)seldata->data;
}
我从这行代码中调用此函数
g_signal_connect(view, "drag_data_received",G_CALLBACK(view_onDragDataReceived), liststore);
我遇到的问题是,当我尝试在另一个函数中使用该pathh变量时,我发现它是空的,即使它被声明为全局变量类型char *
答案 0 :(得分:0)
试试这种方式
struct SelectionData
{
GtkListStore *listStore;
gchar *path;
}
然后在调用函数
中struct SelectionData *data;
data = malloc(sizeof(*data));
if (data == NULL)
handleMallocFailureAndPleaseDoNotContinue();
data->listStore = liststore;
data->path = NULL;
g_signal_connect(view, "drag_data_received",G_CALLBACK(view_onDragDataReceived), data);
然后
void view_onDragDataReceived(GtkWidget *wgt, GdkDragContext *context, int x, int y,GtkSelectionData *seldata, guint info, guint time, gpointer userdata)
{
GtkTreeModel *model;
GtkTreeIter iter;
SelectionData *selectionData;
size_t length;
selectionData = (SelectionData *)userdata;
model = GTK_TREE_MODEL(selectionData->liststore);
gtk_list_store_append(GTK_LIST_STORE(model), &iter);
gtk_list_store_set(GTK_LIST_STORE(model), &iter, COL_URI,(gchar*)seldata->data, -1);
length = strlen((char*)seldata->data);
if (selectionData->path != NULL) /* for subsequent calls */
free(selectionData->path);
selectionData->path = malloc(1 + length);
if (selectionData->path != NULL)
memcpy(selectionData->path, seldata->data, 1 + length);
}
然后您可以在其他地方访问selectionData
,从而访问path
字段,在您完成使用后必须free
d。
尽量避免使用全局变量。
您也可以使用相同的技术将seldata->data
复制到pathh
全局变量中,但重新考虑您的设计并尝试不使用pathh
全局变量,因为您将要使用malloc
为字符串分配空间,全局变量将是指向它的指针,因此理解你必须free
的位置和方式将非常困难。