你可以提供一個包裝,露出了C++類的C-API:
Something.h:
class Something {
protected:
int x;
public:
Something() { x = 0; }
void setX(int newX) { x = newX; }
int getX() const { return x; }
};
wrapper.h:
#pragma once
typedef void *SOMETHING;
#ifdef __cplusplus
extern "C" {
#endif
SOMETHING createSomething();
void destroySomething(SOMETHING something);
void setSomethingX(SOMETHING something, int x);
int getSomethingX(SOMETHING something);
#ifdef __cplusplus
} // extern "C"
#endif
wrapper.cpp:
#include <Something.h>
#include "wrapper.h"
SOMETHING createSomething() {
return static_cast<SOMETHING>(new Something());
}
void destroySomething(SOMETHING something) {
delete static_cast<Something *>(something);
}
void setSomethingX(SOMETHING something, int x) {
static_cast<Something *>(something)->setX(x);
}
int getSomethingX(SOMETHING something) {
return static_cast<Something *>(something)->getX();
}