[英]How to pass multiple arguments to pcap_loop()/pcap_handler()?
I need to pass two pointers of different types to pcap_loop() so that the pcap_handler can read/modify that data. 我需要将两个不同类型的指针传递给pcap_loop(),以便pcap_handler可以读取/修改该数据。
pcap_loop() looks like: pcap_loop()看起来像:
int pcap_loop(pcap_t *p, int cnt, pcap_handler callback, u_char *user);
...and takes arguments through u_char * user
and passes those arguments on to pcap_handler callback
which looks like: ...并通过
u_char * user
接收参数,并将这些参数传递给pcap_handler callback
,如下所示:
void pcap_handler(u_char *user, const struct pcap_pkthdr *h, const u_char *bytes);
So how can I pass multiple arguments through a single u_char pointer? 那么,如何通过单个u_char指针传递多个参数呢? I tried passing them as an array of u_char pointers...
我试图将它们作为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);
}
...but (not surprisingly) got u_char * array[]
-> u_char *
conversion errors. ...但(并不奇怪)得到了
u_char * array[]
-> u_char *
转换错误。 I also got warned about casting from a smaller type ( u_char *
) to a larger type ( class1 *
, class2 *
). 我还被警告要从较小的类型(
u_char *
)转换为较大的类型( class1 *
, class2 *
)。
What's the correct way to be doing this? 正确的做法是什么?
The problem here is that you are trying to pass an array of u_char pointers ( u_char**
) to a parameter that expects an u_char array/pointer ( u_char*
). 这里的问题是,您试图将u_char指针(
u_char**
)数组传递给需要u_char数组/指针( u_char*
)的参数。 (I'm a bit surprised they use u_char pointers as usually these kind of callbacks rely on void pointers, but that's beside the point.) (让我惊讶的是它们使用u_char指针,因为通常这类回调依赖于void指针,但这并不重要。)
What you need to do is one of two: Either you encapsulate your pointers in a struct. 您需要执行以下两项操作之一:将指针封装在结构中。 Or, you do a bit of "creative casting".
或者,您做了一些“创造性的铸造”。
Struct: 结构:
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));
Or you become a bit more creative with the array: 否则,您将变得更有创意:
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));
Once you are casting back you need to use something like: 撤消内容后,您需要使用以下方法:
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]);
}
Or something similar for the struct. 或类似的结构。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.