共 1 篇文章

标签:Linux下C语言如何调用动态库?教你简单实现 (linux c调用动态库)

Linux下C语言如何调用动态库?教你简单实现 (linux c调用动态库)

动态库是Linux下常用的一种共享库,与静态库不同,它在程序运行时才会被载入内存,并在程序退出时卸载,因此相比静态库可以节省内存空间。动态库有很多种类型,例如共享目标文件(.so)和动态链接库(.dll)等。C语言支持通过调用动态库中的函数来实现代码重用,本文将简单介绍如何在Linux下使用C语言调用动态库。 一、动态库的创建 在Linux下创建动态库的方法如下: $ gcc -shared -o libtest.so test.c 其中,-shared指示编译器生成一个共享目标文件,-o指示输出文件名为libtest.so,test.c为源码文件名。 二、C语言调用动态库 为了调用动态库中的函数,需要在C程序中声明函数的原型,并使用dlopen()、dlsym()和dlclose()等系统调用来打开、查找和关闭动态库。 首先声明函数原型,例如test.c中定义了一个名为test()的函数: “`c #include void test() { printf(“Hello, World!\n”); } “` 然后,在调用test()函数之前,需要使用dlopen()函数来打开动态库,并将其句柄存储在一个void类型的指针中: “`c #include int mn() { void* handle = dlopen(“./libtest.so”, RTLD_LAZY); if (!handle) { printf(“%s\n”, dlerror()); return 1; } typedef void (*func_t)(); func_t func = (func_t)dlsym(handle, “test”); if (!func) { printf(“%s\n”, dlerror()); return 1; } func(); dlclose(handle); return 0; } “` 在上述代码中,我们首先使用dlopen()函数打开了名为libtest.so的动态库,如果打开失败则输出错误信息,并退出程序。然后,使用dlsym()函数查找名为test的函数,并将其转换为一个函数指针,最后通过函数指针调用test()函数。需要注意的是,dlsym()函数会返回一个void指针,需要将其显式转换为正确的函数指针类型。使用dlclose()函数关闭动态库句柄。 三、完整示例代码 test.c: “`c #include void test() { printf(“Hello, World!\n”); } “` mn.c: “`c #include #include int mn() { void* handle = dlopen(“./libtest.so”, RTLD_LAZY); if (!handle) { printf(“%s\n”, dlerror()); return 1; } typedef void (*func_t)(); func_t func = (func_t)dlsym(handle, “test”); if (!func) { printf(“%s\n”, dlerror()); return 1; } func(); dlclose(handle); return 0; } “` 编译: $ gcc...

技术分享