Chinaunix首页 | 论坛 | 博客
  • 博客访问: 413126
  • 博文数量: 116
  • 博客积分: 7087
  • 博客等级: 少将
  • 技术积分: 1175
  • 用 户 组: 普通用户
  • 注册时间: 2005-02-19 23:32
文章分类

全部博文(116)

文章存档

2012年(1)

2011年(2)

2010年(10)

2009年(21)

2008年(18)

2007年(12)

2006年(21)

2005年(31)

我的朋友

分类:

2005-10-25 21:38:23

用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< }

};

extern "C" void hello() {
    std::cout << "hello" << "mac"<<' ';
    db t;
    t.showme();

}
 

这个就是用c++写的动态库.技巧就是声明一个全局函数,通过这个全局函数去调用类.当然,这个声明的时候要用 extern "C"来限定一下,这样在编译的时候,名字不会发生改变.

编译命令如下:

g++ -shared hello.cpp -o hello.dll

gcc main.cpp -o main.exe

这个程序是在cygwin下面调试的.

阅读(1089) | 评论(0) | 转发(0) |
给主人留下些什么吧!~~