gpt4 book ai didi

c++ - 如何将多个参数传递给 pcap_loop()/pcap_handler()?

转载 作者:行者123 更新时间:2023-11-27 23:04:06 25 4
gpt4 key购买 nike

我需要将两个不同类型的指针传递给 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/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com