动态库的编写和使用(linux下)

1、动态库的编写和编译
(1)编写外部接口的时候必须添加 “extern “C” ”
如:

#define STDCALL __attribute__((__stdcall__))
extern "C" 
{
    int STDCALL init(const TCHAR *dbfile);
}

(2)编译成动态库

g++ -shared -fPIC -o libcommondll.so common.o 

2、动态库的使用
(1)先使用 typedef 对要使用的函数起个别名

typedef int (*df_init)(const char *dbfile);

(2)加载动态库,主要使用两个函数

//打开动态库文件
void *hso = dlopen("./libcommondll.so", RTLD_LAZY);

//获取动态库中的函数地址
df_init dfInit = (df_init)dlsym(hso, "init");

例子(动态库):
common.h

#include <stdio.h>

#define STDCALL __attribute__((__stdcall__))
extern "C"
 {
    int STDCALL init(const TCHAR *dbfile);
 }

common.cpp

#include "common.h"

int init(const TCHAR *dbfile) 
{
	printf("hello world!\n");
	return 0;
}

例子(使用动态库):
test.cpp

#include <stdio.h>
#include <dlfcn.h>

int main()
{
	typedef int (*df_init)(const char *dbfile);
	//加载动态库
	void *hso = dlopen("./libdfcommondll.so", RTLD_LAZY);
	if(!hso)
	{
	    printf("dlopen failed:%s\n", dlerror());
		return 0;
	}
	//获取动态库中函数地址
	df_init dfInit = (df_init)dlsym(hso, "init");
	//调用动态库中函数
	df_init (NULL);
	return 0;
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值