平台和网站有什么区别seo推广的特点
从Linux设备树读取字符串信息
在Linux内核中,从设备树(DTS)中读取字符串信息,通常使用内核提供的设备树解析API。这些API主要位于<linux/of.h>
头文件中。
常用函数解析
1. of_get_property
- 获取设备树中的属性。
- 原型:
const void *of_get_property(const struct device_node *np, const char *name, int *lenp);
- 参数:
np
: 设备树节点指针。name
: 属性名。lenp
: 输出该属性的长度指针。
- 返回值:
- 成功时,返回指向属性值的指针;失败时返回NULL。
示例:
const char *string_val;
int len;string_val = of_get_property(np, "my-string-property", &len);
if (!string_val)pr_err("Failed to read property 'my-string-property'\n");
elsepr_info("Property value: %s\n", string_val);
2. of_property_read_string
- 直接读取设备树中的字符串属性。
- 原型:
int of_property_read_string(const struct device_node *np, const char *propname, const char **out_string);
- 参数:
np
: 设备树节点指针。propname
: 属性名。out_string
: 输出的字符串指针。
- 返回值:
- 成功返回0;失败返回负值(如
-EINVAL
)。
- 成功返回0;失败返回负值(如
示例:
const char *string_val;if (of_property_read_string(np, "my-string-property", &string_val)) {pr_err("Failed to read string property\n");
} else {pr_info("String property value: %s\n", string_val);
}
3. of_property_read_string_array
- 用于读取多个字符串属性(以空格分隔的字符串数组)。
- 原型:
int of_property_read_string_array(const struct device_node *np, const char *propname, const char **out_strings, size_t sz);
- 参数:
np
: 设备树节点指针。propname
: 属性名。out_strings
: 字符串数组指针。sz
: 最大字符串数量。
- 返回值:
- 成功返回实际读取的字符串数量;失败返回负值。
示例:
const char *strings[3];
int count;count = of_property_read_string_array(np, "my-strings-property", strings, 3);
if (count < 0) {pr_err("Failed to read string array\n");
} else {for (int i = 0; i < count; i++) {pr_info("String[%d]: %s\n", i, strings[i]);}
}
流程示例
假设DTS文件如下:
example-node {compatible = "example,device";my-string-property = "example-string";my-strings-property = "string1", "string2", "string3";
};
在驱动代码中:
static int example_probe(struct platform_device *pdev)
{struct device_node *np = pdev->dev.of_node;const char *string_val;if (!np) {dev_err(&pdev->dev, "No device tree node found\n");return -EINVAL;}// 读取单个字符串if (of_property_read_string(np, "my-string-property", &string_val)) {dev_err(&pdev->dev, "Failed to read 'my-string-property'\n");} else {dev_info(&pdev->dev, "Property value: %s\n", string_val);}// 读取字符串数组const char *strings[3];int count = of_property_read_string_array(np, "my-strings-property", strings, ARRAY_SIZE(strings));if (count < 0) {dev_err(&pdev->dev, "Failed to read 'my-strings-property'\n");} else {for (int i = 0; i < count; i++) {dev_info(&pdev->dev, "String[%d]: %s\n", i, strings[i]);}}return 0;
}
常见问题
- 设备树节点不存在:
- 确保设备树节点被正确绑定到驱动中,可以通过
compatible
属性匹配。
- 确保设备树节点被正确绑定到驱动中,可以通过
- 属性不存在:
- 确保DTS中定义了对应的属性名称,并符合读取代码中的匹配。
通过上述方法,可以方便地从设备树中读取字符串信息,并用于设备驱动的配置和初始化。