1.制作so文件:libadd_c.so
add.c:
int add(int a, int b)
{
return a + b;
}
编译:
gcc -shared -fpic -lm -ldl -o libadd_c.so add.c
2.编写测试函数
test.cpp
#include <stdio.h>
#include <dlfcn.h>
#include <stdlib.h>
#include <iostream>
using namespace std;
int main()
{
int a = 0;
void *handle = dlopen("./libadd_c.so", RTLD_LAZY);
if(!handle)
{
printf("open lib error\n");
cout<<dlerror()<<endl;
return -1;
}
typedef int (*add_t)(int a, int b);
add_t add = (add_t) dlsym(handle, "add");
if(!add)
{
cout<<dlerror()<<endl;
dlclose(handle);
return -1;
}
a = add(3, 4);
printf("a = %d\n",a);
dlclose(handle);
return 0;
}
编译:
g++ test.cpp -ldl -o test
3.运行
./test