心胸决定格局,眼界决定境界...

linux用c++调用动态库

1.4 用c++动态方式调用动态库libsthc.so:
/*cppdltest.cpp*/
#include "stdio.h"
#include "stdlib.h"
#include "dlfcn.h"   //也是用的这个文件,和c一样
 
int main(void)
{
         void *handle;
         int (*fcn)(int x, int y);
         const char *errmsg;
        
         /* open the library */
         handle = dlopen("libsthc.so", RTLD_NOW);
         if(handle == NULL)
         {
                   fprintf(stderr, "Failed to load libsthc.so: %s\n", dlerror());
                   return 1;
         }
         dlerror();
 
         *(void **)(&fcn) = dlsym(handle, "add");     //ok
         //fcn = dlsym(handle, "add");                        //not ok in c++
         if((errmsg = dlerror()) != NULL)
         {
                   printf("%s\n", errmsg);
                   return 1;
         }
         printf("%d\n", fcn(1, 5));
        
         dlclose(handle);
         return 0;
}
posted @ 2014-11-12 11:41  WELEN  阅读(558)  评论(0)    收藏  举报