Chinaunix首页 | 论坛 | 博客
  • 博客访问: 413206
  • 博文数量: 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)

我的朋友

分类:

2006-09-29 16:37:04

用c++开发的动态库,c能访问吗?
答案是可以.
具体怎么做?
 
请看以下例子:
#include
class car
{
  public:
    void show()
    {
      std::cout<<"hello,world!"<    }
};
extern "C" void hello()
{
    car *a=new car();
    a->show();
    delete a;
    return;
}
以上是一个C++写的例子,我们可以通过以下命令将其编译成为一个动态库
aCC -AA +DD64 -b +z -g -lCsup_v2 -lstd_v2 -lc car.cpp -o libcar.sl
 
#include
#include
int main() {
    int i=0;
    void* handle = dlopen("/tmp/libcar.sl", RTLD_LAZY);
    if (!handle) {
        printf("cannot open library:%s\n",dlerror());
        return 1;
    }
    typedef void (*showhello_t)();
    dlerror();
    showhello_t hello = (showhello_t) dlsym(handle, "hello");
    const char *dlsym_error = dlerror();
    if (dlsym_error) {
        dlclose(handle);
        return 1;
    }
    hello();
    dlclose(handle);
    printf("handle closed!\n");
    return 0;
}
以上是调用动态库的代码,是个C程序.我们可以用以下命令产生执行文件:
cc +DD64 -g test.c -o t
 
执行t的时候,就会调用相应的动态库.唯一有缺憾的地方就是最后会core dump.就是在最后退出程序的时候.不知道为什么.如果有人愿意指点,就太好了.
 
(以上程序在hp-ux下编译通过)
 
 
 
 
 
 
 
 
阅读(1519) | 评论(1) | 转发(0) |
0

上一篇:如何写Makefile

下一篇:常用英语学习

给主人留下些什么吧!~~