免费注册 查看新帖 |

Chinaunix

  平台 论坛 博客 文库
最近访问板块 发新帖
查看: 1451 | 回复: 0
打印 上一主题 下一主题

c和c++的合作 [复制链接]

论坛徽章:
0
跳转到指定楼层
1 [收藏(0)] [报告]
发表于 2005-10-25 21:38 |只看该作者 |倒序浏览
用c去调用c++的函数库,是我一直想做的事情.今天晚上有了头绪.
main.c
#include
#include
int main()
{
  printf("C++ dlopen demo
");
  printf("Opening hello.so...
");
      void* handle = dlopen("./hello.dll", RTLD_LAZY);
   
      if (!handle) {
          fprintf(stderr, "Cannot open library: %d
" , dlerror());
          return 1;
       }
      printf("Loading symbol hello...
");
      typedef void (*hello_t)();
      hello_t hello = (hello_t) dlsym(handle, "hello");
      if (!hello) {
          fprintf(stderr, "Cannot load symbol 'hello': %d
" ,dlerror());
          dlclose(handle);
          return 1;
      }  
      // use it to do the calculation
   printf("Calling hello...
");
   hello();
   
      // close the library
   printf("Closing library...
");
       dlclose(handle);  
}
以上程序是用c写的,它的功能很简单,就是用dlopen打开一个动态库,调用其中的一个函数.
如果这个动态库用c来写,则一点也不希奇.除非用c++来写,才有一点点看头.
hello.cpp
#include
#include
using namespace std;
class db
{
private:
string a;
public:
db()
{
  a="abc";
}
~db()
{
  a="";
}
void showme()
{
  cout
这个就是用c++写的动态库.技巧就是声明一个全局函数,通过这个全局函数去调用类.当然,这个声明的时候要用 extern "C"来限定一下,这样在编译的时候,名字不会发生改变.
编译命令如下:
g++ -shared hello.cpp -o hello.dll
gcc main.cpp -o main.exe
这个程序是在cygwin下面调试的.


本文来自ChinaUnix博客,如果查看原文请点:http://blog.chinaunix.net/u/4353/showart_53463.html
您需要登录后才可以回帖 登录 | 注册

本版积分规则 发表回复

  

北京盛拓优讯信息技术有限公司. 版权所有 京ICP备16024965号-6 北京市公安局海淀分局网监中心备案编号:11010802020122 niuxiaotong@pcpop.com 17352615567
未成年举报专区
中国互联网协会会员  联系我们:huangweiwei@itpub.net
感谢所有关心和支持过ChinaUnix的朋友们 转载本站内容请注明原作者名及出处

清除 Cookies - ChinaUnix - Archiver - WAP - TOP