下面是一个使用 GDBus 的简单示例:
首先,确保已经安装了 GDBus 的开发包。在 Ubuntu 上,可以使用以下命令进行安装:
```
sudo apt-get install libgio2.0-dev
```
然后,创建一个名为 `example-service.c` 的源文件,并添加以下内容:
```c
#include <gio/gio.h>
#include <glib.h>
GVariant *handle_hello(GDBusConnection *connection, const gchar *sender, const gchar *object_path, const gchar *interface_name, const gchar *method_name, GVariant *parameters, GDBusMethodInvocation *invocation, gpointer user_data)
{
g_print("Received hello call from %s\n", sender);
gchar *reply = g_strdup_printf("Hello, %s!", g_variant_get_string(parameters, NULL));
g_dbus_method_invocation_return_value(invocation, g_variant_new("(s)", reply));
g_free(reply);
return NULL;
}
int main()
{
GMainLoop *loop;
GDBusNodeInfo *introspection_data;
GDBusInterfaceInfo *interface_info;
GDBusInterfaceVTable interface_vtable = {
.method_call = handle_hello,
};
GError *error = NULL;
gchar *introspection_xml =
"<node>"
" <interface name='com.example.ExampleService'>"
" <method name='Hello'>"
" <arg type='s' name='name' direction='in' />"
" <arg type='s' name='response' direction='out' />"
" </method>"
" </interface>"
"</node>";
introspection_data = g_dbus_node_info_new_for_xml(introspection_xml, &error);
if (error != NULL)
{
g_print("Unable to create introspection data: %s\n", error->message);
return 1;
}
interface_info = g_dbus_node_info_lookup_interface(introspection_data, "com.example.ExampleService");
if (interface_info == NULL)
{
g_print("Unable to lookup interface info\n");
return 1;
}
GDBusConnection *connection = g_bus_get_sync(G_BUS_TYPE_SESSION, NULL, &error);
if (connection == NULL)
{
g_print("Unable to get bus connection: %s\n", error->message);
return 1;
}
guint registration_id = g_dbus_connection_register_object(
connection,
"/com/example/ExampleObject",
interface_info,
&interface_vtable,
NULL,
NULL,
NULL);
if (registration_id == 0)
{
g_print("Unable to register object\n");
return 1;
}
loop = g_main_loop_new(NULL, FALSE);
g_main_loop_run(loop);
g_object_unref(introspection_data);
g_object_unref(connection);
g_main_loop_unref(loop);
return 0;
}
```
接下来,使用以下命令编译并执行示例:
```bash
gcc example-service.c -o example-service `pkg-config --libs --cflags gio-2.0`
./example-service
```
这个示例创建了一个名为 `com.example.ExampleService` 的 D-Bus 服务,提供一个 `Hello` 方法,该方法接收一个字符串作为输入,并返回一个包含字符串的元组。当有客户端调用 `Hello` 方法时,服务端会打印接收到的消息并返回一个带有问候信息的元组。
要测试这个示例,可以使用 `gdbus` 命令行工具:
```bash
gdbus call --session --dest com.example.ExampleService --object-path /com/example/ExampleObject --method com.example.ExampleService.Hello "John"
```
你应该会看到服务端打印出 `Received hello call from ...` 的消息,并返回 `Hello, John!`。