这是理论上的问题。我知道最好的做法可能是使用共享库。但是我遇到了这个问题,似乎无法在任何地方找到答案。
如何构造代码并以ELF格式编译C / C ++程序,以便可以加载该程序dlopen()
?
例如,如果一个可执行文件包含某个功能的实现,int test()
而我想从程序中调用此功能(最好获取功能的结果),那么即使有可能,我将如何去做呢?
用伪代码可以将其描述如下:
ELF可执行源:
void main() {
int i = test();
printf("Returned: %d", i);//Prints "Returned: 5"
}
int test() {
return 5;
}
外部程式:
// ... Somehow load executable from above
void main() {
int i = test();
printf("Returned: %d", i);//Must print "Returned: 5"
}
根据注释和其他答案中提供的链接,此处无需链接这些程序的编译时间即可完成该工作:
test1.c:
#include <stdio.h>
int a(int b)
{
return b+1;
}
int c(int d)
{
return a(d)+1;
}
int main()
{
int b = a(3);
printf("Calling a(3) gave %d \n", b);
int d = c(3);
printf("Calling c(3) gave %d \n", d);
}
test2.c:
#include <dlfcn.h>
#include <stdio.h>
int (*a_ptr)(int b);
int (*c_ptr)(int d);
int main()
{
void* lib=dlopen("./test1",RTLD_LAZY);
a_ptr=dlsym(lib,"a");
c_ptr=dlsym(lib,"c");
int d = c_ptr(6);
int b = a_ptr(5);
printf("b is %d d is %d\n",b,d);
return 0;
}
编译:
$ gcc -fPIC -pie -o test1 test1.c -Wl,-E
$ gcc -o test2 test2.c -ldl
执行结果:
$ ./test1
Calling a(3) gave 4
Calling c(3) gave 5
$ ./test2
b is 6 d is 8
参考文献:
PS:为了避免符号冲突,导入的符号和它们分配给它们的指针最好具有不同的名称。在这里查看评论。
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句