从“C”代码调用“C++”类成员函数

问题描述 投票:0回答:1

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

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

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

c++ c
1个回答
36
投票

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() {
    try { return new C(); }
    catch (...) { return nullptr; }
}
void C_Destroy( void* thisC ) {
   delete static_cast<C*>(thisC);
}
bool C_foo( void* thisC, int arg ) {
   return static_cast<C*>(thisC)->foo( arg );
}

还有很多很棒的文档。第一个我碰到的可以在这里找到。

© www.soinside.com 2019 - 2024. All rights reserved.