日期:2014-05-16 浏览次数:20930 次
现在需要使用共享对象实现通过配置文件生成类对象的功能 , 写了一些代码大家看一下 ======================getstr.h============================= #ifndef __GET_STR_H__ #define __GET_STR_H__ class Obj { public: int b; char *a; Obj(); int c(); }; #ifdef SHARED typedef bool (*GetStr)(char* str,int len); typedef Obj* (*GetObj)(); #else extern "C" { bool GetStr(char* str,int len); Obj* GetObj(); } #endif #endif ========================================================== ========================getstr.cpp================================= #include"string.h" #include"getstr.h" #include"stdio.h" Obj::Obj() { a = new char[100]; b = 100; printf("indl"); } int Obj::c() { a[0] = '!'; a[1] = 0; return 20; } extern "C" { bool GetStr(char* str,int len) { if(len < 10) return false; else strcpy(str,"1234567890"); return true; } Obj* GetObj() { return new Obj(); } } bool ReadStr(char* str,int len) { if(len < 10) return false; else strcpy(str,"1234567890"); return true; } ============================================================================= ================================dy.cpp============================================ #include"stdio.h" #include"dlfcn.h" /*share object interface file*/ #define SOFILE "/home/jameschen/Documents/ShareObject/libMyShareObject.so.1.0" #define SHARED #include"getstr.h" int main() { void *dp; char *error; GetStr getstr; GetObj getobj; puts("share object test"); dp = dlopen(SOFILE,RTLD_LAZY); if(dp==NULL) { printf("\nerror: %s\n",dlerror()); return -1; } getstr = (GetStr)dlsym(dp,"GetStr"); getobj = (GetObj)dlsym(dp,"GetObj"); error = dlerror(); if(error) { printf("\nerror: %s\n",error); return -1; } char test[11] = {0}; getstr(test,10); Obj *obj = getobj(); printf("obj.a is %s\n",obj->a); printf("obj.b is %d\n",obj->b); obj->c(); [color=#FF0000]这里报错了[/color] printf("obj.a is %s\n",obj->a); printf("obj.b is %d\n",obj->b); printf("current string: %s \n",test); dlclose(dp); return 0; }