为什么我会收到"错误:无效转换来自' void *'到' nlattr *'"当我使用" nla_for_each_nested"在嵌套数组上?

时间:2016-07-20 20:55:59

标签: c++ netlink

我使用libnl3nl80211.h获取连接无线接口的可用频段。

当我尝试编译时,我得到error: invalid conversion from ‘void*’ to ‘nlattr*’。 IDE(CLion)也在抱怨行nla_for_each_nested(nl_band, tb_msg[NL80211_ATTR_WIPHY_BANDS], rem_band)并说incompatible pointer type 'nlattr *' and 'void *'

被视为void *的内容是pos = nla_data(nla)中的/usr/include/libnl3/netlink/attr.h被视为void *

编译错误:

/home/username/Documents/Development/appname/fs_nl80211Class.cpp: In function ‘int callback(nl_msg*, void*)’:
/usr/include/libnl3/netlink/attr.h:328:21: error: invalid conversion from ‘void*’ to ‘nlattr*’ [-fpermissive]
  for (pos = nla_data(nla), rem = nla_len(nla);
                     ^

libnl3/netlink/attr.h文件中的宏:

#define nla_for_each_nested(pos, nla, rem) \
    for (pos = nla_data(nla), rem = nla_len(nla); \
         nla_ok(pos, rem); \
         pos = nla_next(pos, &(rem)))

我的代码:

static int callback(struct nl_msg *msg, void *arg) {

    genlmsghdr *gnlh = (genlmsghdr *) nlmsg_data(nlmsg_hdr(msg));

    struct nlattr *tb_msg[NL80211_ATTR_MAX + 1];
    struct nlattr *tb_band[NL80211_BAND_ATTR_MAX + 1];

    struct nlattr *nl_band;

    int rem_band;
    static int last_band = -1;
    static bool band_had_freq = false;

    nla_parse(tb_msg, NL80211_ATTR_MAX, genlmsg_attrdata(gnlh, 0), genlmsg_attrlen(gnlh, 0), NULL);

    if (tb_msg[NL80211_ATTR_WIPHY_BANDS]) {

        // macro from libnl3/netlink/attr.h
        nla_for_each_nested(nl_band, tb_msg[NL80211_ATTR_WIPHY_BANDS], rem_band) {
            if (last_band != nl_band->nla_type) {
                cout << ("Band %d:", nl_band->nla_type) << endl;
                band_had_freq = false;
            }
            last_band = nl_band->nla_type;

            nla_parse(tb_band,
                      NL80211_BAND_ATTR_MAX,
                      nla_data(nl_band),
                      nla_len(nl_band), NULL);

            if (tb_band[NL80211_BAND_ATTR_FREQS]) {
                if (!band_had_freq) {
                    cout << "Frequencies:" << endl;
                    band_had_freq = true;
                }
            }
        }
    }

    //nl_msg_dump(msg, stdout);

    return NL_SKIP;
}

1 个答案:

答案 0 :(得分:0)

问题是由于从void *到nlattr *的隐式类型转换,g ++无法使用nla_for_each_nested宏编译代码。

请参阅libnl list中的链接:

http://lists.infradead.org/pipermail/libnl/2016-February/002096.html

nla_for_each_nested宏中的修复是为nla_for_each_nested宏添加类型转换。

更改自:

for (pos = nla_data(nla), rem = nla_len(nla); \

要:

for (pos = (struct nlattr *) nla_data(nla), rem = nla_len(nla); \