-2

我正在尝试定义一个函数指针来调用具有不同参数的多个函数,但现在我坚持我的想法是否有人有想法或可以看到我做错了什么,因为我不能:微笑:如果你会非常有帮助可以帮我。

//Goal:  Calling the sum function from the function pointer with the t1 struct as parameter
//Theory:  As my theory after first param the function will go  -4 down in memory and look for the second variable but nope
float sum(float &x, float &y) //a random test-foo function
{
    float s = x + y;
    printf_s("(%X)x: %f + (%X)y: %f | Result: %f\n",&x, x, &y, y, s);
    return s;

}
typedef float(*fsum)(void* params);
fsum fsm = (fsum)∑
struct t1 {
    float f[2]; //the params will be here
}tx1;
int main()
{
    tx1.f[0] = 4.3; tx1.f[1] = 2;  //setting values on the params
    printf_s("tx1: 0x%X\ntx1.f[0]: 0x%X\ntx1.f[1]: 0x%X\n", &tx1, &tx1.f[0], &tx1.f[1]);
    fsm(&tx1.f[0]); //calling the function pointer
    getchar();
   return 0;
}

我的主要目标是稍后使用它来调用具有不同参数的不同函数,只需 1 个函数指针和 1 个指向参数的指针,例如:

if(statement1)
    funcPointer = func1; //change the func pointer to point to func1
else if(statement1)
    funcPointer = func2;  //change the func pointer to point to func2
funcPointer(paramPointer); //call the function pointer

第二个问题:假设我有一个我用 C++ 编写的 .dll,它有一个名为“fuu”的函数,我在另一个进程中加载​​了 dll,如何使用第二个不同的 C++ dll 加载“fuu”函数?

4

1 回答 1

0

我不喜欢你的模式,但如果你真的坚持,你可以使用多态性。

class BaseProcessor{
      public:
      virtual float func(void *); };

class Processor1 : public BaseProcessor {
      public:
      type3 func(void * param){ 
           type3 func1((type1*) param);
      }

      private:
           type3 func1(type1 * param){
            //implementation goes here
           }         };


class Processor2 : public BaseProcessor {
      public:
      type3 func(void * param){ 
           return func2((type2 *) param);
      }

      private:
           type3 func2(type2 * param){
            //implementation goes here
           }
    };

并像这样使用它。

    BaseProcessor * processor;

    if(statement1)
        processor = new Processor1; 
    else if(statement1)
        processor = new Processor2; 

    processor->func(paramPointer);

void *是一个糟糕的 C++ 设计的警告。

如果您没有模棱两可的签名,您可以简单地重载func(),或者只是将实现附加到数据:

class base_t{
    public:
    virtual float sum();
}

class t1 : public base_t {
    public:
    float f[2]; //the params will be here

    sum(){/* Implemenation goes here*/}
};
于 2018-06-28T03:08:48.150 回答