通过LPVOID调用一个函数,最多包含10个不同类型的参数

时间:2017-06-14 16:05:12

标签: c++ c++11 c++14

我需要调用一个函数,其中我有LPVOID和参数个数。此外,我知道参数的类型和位置。 参数可以是int,int *,double,double *,string,string *类型。 由于参数可以是任何顺序,因此可能的模板列表将非常大。返回值始终是布尔值。

bool Func1(int);
bool Func1(int*);
bool Func1(double);
(...)
bool Func2(int,int);
bool Func2(int,int*);
(...)

所以这不是一个选择。我试过使用std :: tuple但没有成功。 以下示例仅适用于带参数的函数(int,double)。

    template <typename R, typename... Args>
    R call(FARPROC fp, Args... args) throw(HRESULT)
    {
        typedef R(__stdcall * function_pointer)(Args...);
        function_pointer P = (function_pointer)fp;
        const auto return_value = (*P)(std::forward<Args>(args)...);
        ().do_cast(fetch_back(args))...);
        return return_value;
     }

(...)
LPVOID function;
int iVal1 = 2;
double dbVal1 = 3.0;
auto t = std::make_tuple(iVal1 , dbVal1);
bool bRes = call<bool>((FARPROC)function, std::get<0>(t), std::get<1>(t));

我在想的是基于某些输入(字符串等)创建std :: tuple的通用方法,例如:auto t = create_tuple(&#34; int,int *,int&#34; )。

2 个答案:

答案 0 :(得分:0)

我有一个提案,但你必须通过它的地址设置double变量,就像指针一样,因为双变量有8个字节,而void指针的大小有x86的4个字节和x64的8个字节。此外,string变量必须设置为指针:

#include "stdafx.h"
#include <string>

using namespace std;

bool Func1(void* arg1, void* arg2, void* arg3, void* arg4, void* arg5, void* arg6)
{
    bool result = false;

    int a1 = (int)arg1;
    int a2 = *(int*)arg2;
    double a3 = *(double*)arg3;
    double* a4 = (double*)arg4;
    string a5 = *(string*)arg5;
    string* a6 = (string*)arg6;

    //Do something...

    return result;
}

int main()
{
    bool(*myFun)(void* arg1, void* arg2, void* arg3, void* arg4, void* arg5, void* arg6);
    myFun = &Func1;
    int a1 = 2;
    int a2 = 3;
    double a3 = 4;
    double* a4 = new double(5);
    string a5= "MyData 1";
    string* a6 = new string("MyData 2");

    bool r = (*myFun)((void*)a1, (void*)&a2, (void*)&a3, (void*)a4, (void*)&a5, (void*)a6);
    return 0;
}

enter image description here

我希望这可以帮到你。

答案 1 :(得分:0)

我的建议,对任何对替代品感兴趣的人......

将LPVOID函数隐藏在有意义的API下,不再直接使用它。

显然,LPVOID函数带有一堆void * ters不是自我记录的,所以提供一些东西。

提供各种构造函数或辅助方法,这些方法接受对LPVOID进行特定低级调用所需的值,并提供将值下移到LPVOID的转换方法。

相关问题