前一篇文章主要介绍了dbus调用的流程,及简单的单工通信,这里记录下双工通信的流程,供后续参考。
定义dbus名称,路径,接口,方法等。
额外注意点:
1. 所有的全局资源必须加锁
2. handle-method-call中 从g_variant_get获得的字符串,不需要自己释放,系统会自动释放,注意如果后续需要使用,必须strdump出来。
#define TEST_DBUS_A "methodA"
#define TEST_DBUS_B "methodB"
#define TEST_DBUS_INTERFACE "com.test.hello"
#define TEST_DBUS_OBJPATH "/com/test/hello"
#define TEST_DBUS_NAME "com.test.hello"
#define TEST_DBUS_TIMEOUT 100000
client
static GDBusConnection *test_client_conn = NULL;
static GDBusNodeInfo *dbus_node_info = NULL;
static pthread_mutex_t callback_info_list_mutex;
GHashTable *g_callback_info_list = NULL;
typedef struct {
void *callback;
void *user_data;
} dbus_client_data;
static void __handle_method_call(GDBusConnection *conn, const gchar *sender,
const gchar *obj_path, const gchar *iface, const gchar *method_name,
GVariant *parameters, GDBusMethodInvocation *invocation, gpointer user_data)
{
printf("sender[%s],obj_path[%s],iface[%s],method_name[%s]", sender,obj_path,iface,method_name);
void* callback_addr = NULL;
void* ud = NULL;
dbus_client_data *dcd = NULL;
pthread_mutex_lock(&callback_info_list_mutex);
dcd = g_hash_table_lookup(g_callback_info_list, method_name);
g_hash_table_remove(g_callback_info_list, dcd);
pthread_mutex_unlock(&callback_info_list_mutex);
if (dcd) {
callback_addr = dcd->callback;
ud = dcd->user_data;
}
if (0 == g_strcmp0(method_name, TEST_DBUS_A)) {
int ret = 0;
char *string1 = NULL;
if (parameters) {
g_variant_get(parameters, "(&s)", &string1);
}
if (callback_addr != NULL) {
((cb)callback_addr)(string1, ud);
} else {
printf("callback address is NULL");
}
g_dbus_method_invocation_return_value(invocation, g_variant_new ("(i)", ret));
} else {
g_dbus_method_invocation_return_error(invocation,
G_DBUS_ERROR, G_DBUS_ERROR_UNKNOWN_METHOD,
"Method %s is not implemented on interface %s", method_name,