返回void*的C++/C函数指针

bry*_*mon 5 c c++ function-pointers

我试图调用一个带参数的函数void(*)(void*, int, const char*),但我无法弄清楚如何将这些参数传递给函数.

例:

void ptr(int);
int function(int, int, void(*)(int));
Run Code Online (Sandbox Code Playgroud)

我试图像这样调用函数:

function(20, 20, ptr(20));
Run Code Online (Sandbox Code Playgroud)

这可能吗?

Art*_*tur 9

你做错了一件事 - 你试图在调用'function'之前调用你的'ptr'函数.你应该做的是只传递一个指向'ptr'的指针并使用'function'中的传递指针调用'ptr',如下所示:

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 );
}
Run Code Online (Sandbox Code Playgroud)

这使:

from function a=[10] b=[2]
from ptr [10]
from function a=[20] b=[2]
from ptr [20]
Run Code Online (Sandbox Code Playgroud)

这就是你想要的

对于

function(20, 20, ptr(20));
Run Code Online (Sandbox Code Playgroud)

工作 - 你必须要像:

// '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);
Run Code Online (Sandbox Code Playgroud)