c调用c++的类函数

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         //#include "add_c.h"
  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

  • 1
    点赞
  • 7
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值