如何在c里调用c++的类函数

来源:互联网 发布:原生js获取data属性 编辑:程序博客网 时间:2024/05/07 10:02

http://bbs.sjtu.edu.cn/bbscon?board=C&file=M.1300711242.A

 

在c++中定义了一个类,现在需要在c中调用这个类中的函数。

add.h                                                                          
  1
  2 class Add{
  3     public:
  4         Add();
  5         int x,y;
  6         int sum();
  7 };
  8
  9 extern "C"{
 10 int call_add_sum_Cplus(void *pAdd);
 11 void * constructor_add_Cplus();
 12 void destructor_add_Cplus(void * pAdd);
 13 }


add.cpp                                                                        
  1 #include "add.h"
  2     
  3 Add::Add()
  4 {   
  5     x=2;
  6     y=3;
  7 }   
  8     
  9 int Add::sum()
 10 {   
 11     return x+y;
 12 }
 13     
 14 int call_add_sum_Cplus(void *pAdd)
 15 {
 16     return ((Add *)pAdd)->sum();
 17 }
 18
 19     
 20 void * constructor_add_Cplus()
 21 {  
22     Add *p = new Add();
 23     return (void *)p;
 24 }
 25    
 26 void destructor_add_Cplus(void * pAdd)
 27 {  
 28     Add *p = (Add *)pAdd;
 29     delete p;
 30 }
 31    
 32  


add_c.h                                                                       
  1
  2
  3 int call_add_sum_C(void *pAdd);
  4 void * constructor_add_C();
  5 void destructor_add_C(void *pAdd);
  6

add_c.c                                                                       
  1 #include "add_c.h"
  2
  3 int call_add_sum_Cplus(void *pAdd);
  4 void * constructor_add_Cplus();
  5 void destructor_add_Cplus(void * pAdd);
  6
  7 int call_add_sum_C(void *pAdd)
  8 {
  9     return call_add_sum_Cplus(pAdd);
 10 }
 11
 12 void * constructor_add_C()
 13 {
 14     return constructor_add_Cplus();
 15 }
 16
 17
 18 void destructor_add_C(void *pAdd)
 19 {
 20     destructor_add_Cplus(pAdd);
 21 }

main.c                                                                        
  1 #include <stdio.h>
  2
  3 void main(void)
  4 {
  5     void *p = constructor_add_C();
  6     int a = call_add_sum_C(p);
  7     printf("a = %d \n",a);
  8     destructor_add_C(p);
  9 }
 10


Makefile                                                                      
  1 easy:main.o add.o add_c.o
  2     gcc main.o add_c.o add.o -lstdc++ -o easy
  3 main.o:main.c
  4     gcc -c main.c -o main.o
  5 add.o:add.cpp
  6     g++ -c add.cpp -o add.o
  7 add_c.o:add_c.c
  8     gcc -c add_c.c -o add_c.o
  9
 10 clean:
 11     rm *.o

结果
yang@ubuntu:~/Cincludeclass$ ls
add_c.c  add_c.o  add.h  easy    main.o
add_c.h  add.cpp  add.o  main.c  Makefile
yang@ubuntu:~/Cincludeclass$ ./easy
a = 5

原创粉丝点击