通过指针调用函数并在内存块中设置参数

时间:2011-01-17 10:27:15

标签: c++ c

我没有什么问题:

我正在解决通过指针调用函数并在连续内存块中传递给它的问题。   我的目标是让函数命名为例如

CallFunc(void * func,void *params, unsigned int param_length);

我将发送函数指针,指向函数参数的指针以及最终的参数长度,这个调用函数将使用它的参数调用传递的函数。

我想用C / C ++编写这个,但是如果有人知道,如何在其他语言中解决这个问题,支持DLL生成和导出函数,它也会很好。

感谢您的回答,   Ellesmess

P.S。 >我很抱歉我的英语,但我是捷克人,谢谢:o)

3 个答案:

答案 0 :(得分:0)

在不知道您的参数类型的情况下,无法从void *中恢复它们。所以这是不可能的。  您需要更改CallFunc界面。

我不确定这是你需要的,但它正在发挥作用。

template <typename Func>
void CallFunc(Func func)
{
    func();
}

template <typename Func, typename  Arg1_Type>
void CallFunc(Func func,Arg1_Type arg1)
{
    func(arg1);
}

template <typename Func, typename  Arg1_Type, typename  Arg2_Type>
void CallFunc(Func func,Arg1_Type arg1,Arg2_Type arg2)
{
    func(arg1,arg2);
}


//defination of CallFunc untill Arg10 or Arg20 
.....


//some function

void somefunction(int x)
{
std::cout<<x<<std::endl;
}

//and calling it in main

CallFunc(somefunction,7);

答案 1 :(得分:0)

C ++ 0x有可变参数模板,它允许这种魔术:

#include <iostream>
using namespace std ;

template<typename... Args> void CallFunc (void (*func)(Args...), Args... args) {
  func (args...) ;
}

void f (int x, double y) { cout << x << ", " << y << endl ; }

int main() { CallFunc (&f, 123, 5.6) ; }

答案 2 :(得分:0)

好的,再试一次:) 再一次,我不确定这是你需要的东西+我相信你需要改变你的代码风格(因为从你的问题我填补你正在做的事情变得奇怪)。

这是我的解决方案:

#include <iostream>
#include <boost/function.hpp>
using namespace std;

template <typename Ret>
void CallFunc(boost::function<Ret ()> func)
{
    func();
}


template< typename Ret, typename Arg1>
Ret CallFunc(boost::function<Ret (Arg1)> func, void * args[])
{
    Arg1 * arg1= static_cast<Arg1*> (args[0]);
    return func(*arg1);
}

template<typename Ret, typename Arg1,typename Arg2>
Ret CallFunc(boost::function<Ret (Arg1,Arg2)> func, void * args[])
{
    Arg1 * arg1= static_cast<Arg1*> (args[0]);
    Arg2 * arg2= static_cast<Arg2*> (args[1]);
    return func(*arg1,*arg2);
}

int somefunction(int x)
{
    return x*x;
}


int main()
{
    boost::function<int (int)> func(somefunction);
    int x=17;
    void * args[1];
    args[0]=&x;
    int y = CallFunc(func,args );

    std::cout<<y<<std::endl;
    return 0;
}
相关问题