gpt4 book ai didi

c++ - 用 c 方法包装 c++ 方法

转载 作者:行者123 更新时间:2023-11-30 01:41:49 32 4
gpt4 key购买 nike

我有一个类:

class C {
public:
int func1 (int arg1, int arg2) { return 1; }
float func2 (float arg1, float arg2) { return 2; }
} ;

我想为方法 func1 和 func2 创建一个 C 包装函数,然后将其转换为一个 void 函数指针。

typedef void (*Function)(void);
typedef Function *FunctionPtr;

FunctionPtr functions[] = {
(FunctionPtr)&Wrap<&C::func1>::f,
(FunctionPtr)&Wrap<&C::func2>::f
};

之后我可以将它们转换回 C 函数指针并使用它们:

Class C c;

typedef int (*MyIntFunction)(C *c, int arg1, int arg2);
MyIntFunction *mif = (MyIntFunction *)functions[0];
int ri = (*mif)(&c, 1, 2);

typedef float (*MyFloatFunction)(C *c, float arg1, float arg2);
MyFloatFunction *mff = (MyFloatFunction *)functions[1];
float rf = (*mff)(&c, 1, 2);

我一直在试验各种模板魔法,但到目前为止还没有找到正确的方法。

最佳答案

您可以在 C 代码中使用类或模板。要包装 C++ 函数,您必须为每个 C++ 函数创建一个 C 包装器。在标题中:

#ifdef __cplusplus
extern "C" {
#endif

int C_func1( void *obj, int arg1, int arg2 );

#ifdef __cplusplus
}
#endif

.cpp 中:

#ifdef __cplusplus
extern "C" {
#endif

int C_func1( void *obj, int arg1, int arg2 ) {
C *const that = static_cast<C*>(obj);
return that->func1( arg1, arg2 );
}

#ifdef __cplusplus
}
#endif

C::func2 重复,依此类推。

关于c++ - 用 c 方法包装 c++ 方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40791154/

32 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com