返回void *的C ++ / C函数指针 [英] C++/C function pointers that return void*

查看:252
本文介绍了返回void *的C ++ / C函数指针的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图调用一个接受参数 void(*)(void *,int,const char *)的函数,但我不知道

I'm trying to call a function that takes an argument, void(*)(void*, int, const char*), but I cannot figure out how to pass those arguments to the function.

示例:

void ptr(int);
int function(int, int, void(*)(int));

我试图像这样调用函数:

I am trying to call the function like this:

function(20, 20, ptr(20));

这是否可能?

推荐答案

你做的一件事情不正确 - 你试图在调用'function'之前调用你的'ptr'函数。你应该做的是传递一个指针到'ptr',并使用从'function'传递的指针调用'ptr',如下:

You are doing one thing incorrectly - you are trying to invoke your 'ptr' function before invoking 'function'. What you were supposed to do is to pass just a pointer to 'ptr' and invoke 'ptr' using passed pointer from 'function' like that:

void ptr(int x)
{
    printf("from ptr [%d]\n", x);
}

int function(int a, int b , void (*func)(int) )
{
    printf( "from function a=[%d] b=[%d]\n", a, b );
    func(a); // you must invoke function here

    return 123;
}


void main()
{
    function( 10, 2, &ptr );
    // or
    function( 20, 2, ptr );
}

其中:

from function a=[10] b=[2]
from ptr [10]
from function a=[20] b=[2]
from ptr [20]

这是你想要的

用于

function(20, 20, ptr(20));

工作 - 您必须拥有sth:

to work - you would have to have sth like:

// 'ptr' must return sth (int for example)
// if you want its ret val to be passed as arg to 'function'
// this way you do not have to invoke 'ptr' from within 'function'
int ptr(int);
int function(int, int , int);

这篇关于返回void *的C ++ / C函数指针的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆