of_find_node_by_name of_get_child_by_name
时间: 2023-07-23 08:13:29 浏览: 48
`of_find_node_by_name` 和 `of_get_child_by_name` 都是在 Linux 内核中用于操作设备树的函数,但它们的功能和使用方式有一些不同。
`of_find_node_by_name` 函数用于从整个设备树中查找指定名称的节点。它接受一个参数:要查找的节点的名称。如果找到了匹配的节点,则返回该节点的指针;否则返回 NULL。
`of_get_child_by_name` 函数用于从给定的父节点中查找指定名称的子节点。它接受两个参数:父节点和要查找的子节点的名称。如果找到了匹配的子节点,则返回该子节点的指针;否则返回 NULL。
所以,区别在于它们的查找范围。`of_find_node_by_name` 在整个设备树中查找节点,而 `of_get_child_by_name` 只在给定的父节点下查找子节点。
相关问题
gsf_infile_child_by_name使用示例
`gsf_infile_child_by_name` 是一个函数,可以根据指定的名称查找输入文件中的子节点。以下是一个使用示例:
假设我们有一个 XML 格式的输入文件,如下所示:
```
<root>
<child1>
<name>John</name>
<age>30</age>
</child1>
<child2>
<name>Jane</name>
<age>25</age>
</child2>
</root>
```
我们想要获取 `child1` 节点中的 `name` 和 `age` 属性值。可以使用下面的代码:
```c
#include <stdio.h>
#include <string.h>
#include <gsf.h>
int main() {
GsfInputFile* infile = gsf_input_file_new("input.xml");
if (infile == NULL) {
printf("Failed to open input file.\n");
return 1;
}
GsfXmlNode* child1 = gsf_infile_child_by_name(infile, "child1");
if (child1 == NULL) {
printf("Failed to find child1 node.\n");
gsf_input_file_free(infile);
return 1;
}
GsfXmlNode* name = gsf_node_child_by_name(child1, "name");
if (name == NULL) {
printf("Failed to find name node.\n");
gsf_input_file_free(infile);
return 1;
}
GsfXmlNode* age = gsf_node_child_by_name(child1, "age");
if (age == NULL) {
printf("Failed to find age node.\n");
gsf_input_file_free(infile);
return 1;
}
const char* name_val = gsf_node_get_attr(name, "value");
const char* age_val = gsf_node_get_attr(age, "value");
printf("Name: %s\n", name_val);
printf("Age: %s\n", age_val);
gsf_input_file_free(infile);
return 0;
}
```
在上面的示例中,我们首先使用 `gsf_input_file_new` 函数打开输入文件,然后使用 `gsf_infile_child_by_name` 函数查找名为 `child1` 的子节点。如果找到该节点,我们继续使用 `gsf_node_child_by_name` 函数查找名为 `name` 和 `age` 的子节点。如果都找到了,我们使用 `gsf_node_get_attr` 函数获取这些子节点的属性值,并将其打印出来。
请注意,在实际使用时,应该对返回的指针进行检查,以确保它们不是 NULL。
举例说明of_count_phandle_with_args函数的使用
`of_count_phandle_with_args` 函数用于在设备树(Device Tree)中查找指定名称的节点,并返回该节点下具有指定属性的子节点数量。
以下是一个使用 `of_count_phandle_with_args` 函数的示例:
```c
#include <linux/of.h>
...
struct device_node *parent_node;
int num_children;
parent_node = of_find_node_by_name(NULL, "parent_node");
if (!parent_node) {
printk(KERN_ERR "Cannot find parent_node\n");
return -ENODEV;
}
num_children = of_count_phandle_with_args(parent_node, "child_node", "arg1", 0);
```
在上述示例中,我们首先通过调用 `of_find_node_by_name` 函数查找名为 "parent_node" 的节点,并将其指针存储在 `parent_node` 变量中。如果未找到该节点,则返回错误。
接下来,我们使用 `of_count_phandle_with_args` 函数来查找名为 "child_node" 的节点,并且该节点必须具有一个名为 "arg1" 的属性,其值为 0。函数返回具有这些属性的子节点数量,并将其存储在 `num_children` 变量中。
请注意,`of_count_phandle_with_args` 函数可以与其他函数一起使用,例如 `of_get_property`,以获取更详细的信息。