如何在QT中实现C语言中调用C++的函数

如题所述

C source file的实现。
#include "obj.h"
int main(const int argc, const char **argv){
void *temp_obj = getObj(100);
printString(temp_obj);//实现C语言调用QT/C++UI界面
return (0);
}

写一个C++ source file和c source file都可以共同包含的头文件,如下所示。
#include <stdint.h>
#ifdef __cplusplus
class Obj{
public:
Obj(int32_t a=50)
~Obj();
std::string toString();
private:
int32_t k;
};
#endif
#ifdef __cplusplus
extern "C" {
#endif
void* getObj(int32_t a);
void destroyObj(void *obj);
void printString(void *obj);
#ifdef __cplusplus
}
#endif

C++ source file的实现,其中C语言函数是供C source file调用的。
#include <iostream>
#include <sstream>
#include <iomanip>
#include <stdint.h>
#include "obj.h"
Obj::Obj(int32_t a){
k = a << 1;
}
Obj::~Obj(){
/* don't really need to do anything here */
/* k = 0 only for example purposes */
k = 0;
}
std::string Obj::toString(){
std::ostringstream os;
os << "Obj is currently: " << this->k << std::endl;
return os.str();
}
void* getObj(int32_t a){
Obj *out = new Obj(a);
return ((void*)out);
}
void destroyObj(void* obj){
delete (((Foo*)obj));
}
void printString(void *obj){
std::string s = ((Obj*)obj)->toString();
std::cout << s;
}
Makefile
make file的实现。
CC ?= gcc
CXX ?= g++
CFLAGS = -O0 -g
CXXFLGS = -00 -g
OBJ = main obj
OBJS = $(addsuffix .o,$(OBJ))
all:
make compile
compile:
make $(OBJS)
make objexe
fooexe: $(OBJS)
$(CXX) -o fooexe $(OBJS)
main.o: main.c
$(CC) -c -o main.o main.c
obj.o: obj.cpp
$(CXX) -c -o obj.o obj.cpp
clean:
rm -rf $(OBJS) objexe *.dSYM
温馨提示:答案为网友推荐,仅供参考
相似回答