我有以下函数声明:
typedef void (cback) (scan_results *scan_result, uint8_t *adv_data);
我将函数声明如下:
cback my_cback;
我将my_cback
作为函数输入。然后,我要访问my_cback
的参数。我该如何实现?
答案 0 :(得分:2)
使用我的VC2008,以下文件可以编译并运行:
typedef void (cback) (int *scan_result, int *adv_data);
void f(int *scan_result, int *adv_data)
{
*adv_data= *scan_result;
}
void ftest(cback *g, int k)
{
int l;
g(&k, &l); // call the function passed as argument
printf("%d\n",l);
}
void test(void)
{
int i=3, j;
cback *my_cback= f; // assign f to a function pointer variable
my_cback(&i,&j); // call the function pointer directly
printf("%d\n",j);
ftest(my_cback, 4); // pass the function pointer
}
输出:
3
4
答案 1 :(得分:1)
我将
my_cback
作为函数输入。
然后,我要访问my_cback的参数。我该如何实现?
不仅传递给foobar()
,而且传递给my_cback
的参数传递给函数(下面的my_cback()
)。
#include <stdint.h>
#include <stdio.h>
typedef char *scan_results;
typedef void (cback) (scan_results *scan_result, uint8_t *adv_data);
// Declare function
cback my_cback;
// Define function
void my_cback(scan_results *scan_result, uint8_t *adv_data) {
*scan_result = "Hello";
*adv_data = 42;
}
void foobar(cback foo, scan_results *scan_result, uint8_t *adv_data) {
(foo)(scan_result, adv_data);
// access the arguments
printf("Inside foobar(): scan_result = %s, adv_data = %d\n", *scan_result,
*adv_data);
}
int main() {
scan_results sr;
uint8_t data;
// I give my_cback to a function as an input.
foobar(my_cback, &sr, &data);
// access the arguments
printf("Inside main(): scan_result = %s, adv_data = %d\n", sr, data);
}
输出
Inside foobar(): scan_result = Hello, adv_data = 42
Inside main(): scan_result = Hello, adv_data = 42