Linux下C实现的共享库
1. 共享库的命名:
Windows 下的共享库后缀名为*.dll, Linux下共享库以.so结尾
2. 如何创建共享库?:
$>gcc -Wall -fpic -shared mytestso.c -o mytestso.so
# -fpic: 使输出的对象模块是按照可重定位地址方式生成
3. 如何使用共享库?
3.1 需要事先知道函数名称(字符串)
3.2 在主程序中加载共享库
3.3 获取函数的起始地址(函数指针)
3.4 主程序编译命令
$>gcc -Wall main.c -ldl -o main
# -ldl : 表示的对象模块需要使用共享库
4. 动态连接加载的编程接口
#include
4.1 void *dlopen(const char *filename, int flag);
4.2 void *dlsym(void *handle, char *symbol);
4.3 int dlclose(void *handle);
4.4 const char *dlerror(void);
// file mytestso.h
#include
int GetMax(int a, int b);
int GetInt(char* psztxt);
typedef int GetMax_t(int a, int b);
typedef int GetInt_t(char* psztxt);
// file mytestso.c
int GetMax(int a, int b)
{
if (a > b)
return a;
else
return b;
}
int GetInt(char* psztxt)
{
if ( 0 == psztxt )
{
return -1;
}
return atoi(psztxt);
}
// main.c
#include
#include
#include "mytestso.h"
int main(int argc, char** argv)
{
void* pdlhandle;
char* pszerror;
int a, b;
char* psztxt = "1024";
// open mytestso.so
pdlhandle = dlopen("./mytestso.so", RTLD_LAZY);
if ( 0 != (pszerror = dlerror()) )
{
printf("%s\n", pszerror);
exit(1);
}
// get GetMax func
GetMax_t* GetMax_Ptr = dlsym(pdlhandle, "GetMax");
if ( 0 != (pszerror = dlerror()) )
{
printf("%s\n", pszerror);
exit(1);
}
// get GetInt func
GetInt_t* GetInt_Ptr = dlsym(pdlhandle, "GetInt");
if ( 0 != (pszerror = dlerror()) )
{
printf("%s\n", pszerror);
exit(1);
}
// call func
a = 200;
b = 600;
printf("max=%d\n", GetMax_Ptr(a, b));
printf("txt=%d\n", GetInt_Ptr(psztxt));
// close mytestso.so
dlclose(pdlhandle);
exit(0);
}
阅读(517) | 评论(0) | 转发(0) |