gpt4 book ai didi

c++ - 从 "C++"代码调用 "C"类成员函数

转载 作者:行者123 更新时间:2023-11-30 16:19:06 26 4
gpt4 key购买 nike

我们如何在“C”代码中调用“C++”类成员函数?

我有两个文件.cpp,其中我定义了一些带有成员函数的类和相应的“.h”文件,其中包含一些其他帮助cpp/h文件。

现在我想在“C”文件中调用CPP文件的这些功能。我该怎么做?

最佳答案

C 没有 thiscall 概念。 C 调用约定不允许直接调用 C++ 对象成员函数。

因此,您需要为 C++ 对象提供一个包装 API,该 API 显式而不是隐式地获取 this 指针。

示例:

// C.hpp
// uses C++ calling convention
class C {
public:
bool foo( int arg );
};

C 包装 API:

// api.h
// uses C calling convention
#ifdef __cplusplus
extern "C" {
#endif

void* C_Create();
void C_Destroy( void* thisC );
bool C_foo( void* thisC, int arg );

#ifdef __cplusplus
}
#endif

您的 API 将用 C++ 实现:

#include "api.h"
#include "C.hpp"

void* C_Create() { return new C(); }
void C_Destroy( void* thisC ) {
delete static_cast<C*>(thisC);
}
bool C_foo( void* thisC, int arg ) {
return static_cast<C*>(thisC)->foo( arg );
}

还有很多很棒的文档。第一个I bumped into可以查到here .

关于c++ - 从 "C++"代码调用 "C"类成员函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55699912/

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