作者热门文章
- html - 出于某种原因,IE8 对我的 Sass 文件中继承的 html5 CSS 不友好?
- JMeter 在响应断言中使用 span 标签的问题
- html - 在 :hover and :active? 上具有不同效果的 CSS 动画
- html - 相对于居中的 html 内容固定的 CSS 重复背景?
我需要将两个不同类型的指针传递给 pcap_loop(),以便 pcap_handler 可以读取/修改该数据。
pcap_loop() 看起来像:
int pcap_loop(pcap_t *p, int cnt, pcap_handler callback, u_char *user);
...并通过 u_char * user
获取参数并将这些参数传递给 pcap_handler 回调
,如下所示:
void pcap_handler(u_char *user, const struct pcap_pkthdr *h, const u_char *bytes);
那么如何通过单个 u_char 指针传递多个参数呢?我尝试将它们作为 u_char 指针数组传递...
#include <pcap/pcap.h>
...
void callback(u_char *arg_array, const struct pcap_pkthdr *h, const u_char *bytes) {
class1 * c1_ptr = (class1 *)arg_array[0];
class2 * c2_ptr = (class2 *)arg_array[1];
}
void main() {
...
class1 c1;
class2 c2;
u_char * arg_array[2];
arg_array[0] = (u_char *)&c1;
arg_array[1] = (u_char *)&c2;
pcap_loop(p, cnt, callback, arg_array);
}
...但是(不足为奇)出现了 u_char * array[]
-> u_char *
转换错误。我还收到关于从较小类型 (u_char *
) 转换为较大类型 (class1 *
, class2 *
) 的警告。
执行此操作的正确方法是什么?
最佳答案
这里的问题是您试图将 u_char 指针数组 (u_char**
) 传递给需要 u_char 数组/指针 (u_char*
) 的参数). (我有点惊讶他们使用 u_char 指针,因为通常这类回调依赖于 void 指针,但这不是重点。)
您需要做的是以下两项之一:要么将指针封装在结构中。或者,您进行一些“创意选角”。
结构:
struct cb_struct {
class1 *c1;
class2 *c2;
};
//... In main or wherever
class1 c1;
class2 c2;
cb_struct cb_s = { &c1, &c2 };
pcap_loop( p, cnt, callback, reinterpret_cast<u_char*>(cb_s));
或者你对阵列变得更有创意:
void * arg_arr[2] = { &c1, &c2 }; // Prefer void array so noone actually tries to use your pointers as what u_chars.
pcap_loop( p, cnt, callback, reinterpret_cast<u_char*>(arg_arr));
一旦你回退,你需要使用类似的东西:
void callback(u_char *arg_array, const struct pcap_pkthdr *h, const u_char *bytes) {
void ** arg_arr = reinterpret_cast<void**>(arg_array);
class1 * c1_ptr = reinterpret_cast<class1*>(arg_arr[0]);
class2 * c2_ptr = reinterpret_cast<class2*>(arg_arr[1]);
}
或者类似的结构。
关于c++ - 如何将多个参数传递给 pcap_loop()/pcap_handler()?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24768543/
我是一名优秀的程序员,十分优秀!