简体   繁体   English

如何动态加载自己的库,并在其中调用方法?

[英]How do I load my own library dynamically, and invoke a method in it?

I'd like to write some C code (okay if it only works on Linux) to dynamically load a new shared library, and then invoke a method from it (to be determined at runtime). 我想写一些C代码(好吧,如果它只适用于Linux)来动态加载一个新的共享库,然后从中调用一个方法(在运行时确定)。 It seems this is already possible because java can load native libraries dynamically, and then invoke methods from them. 这似乎已经成为可能,因为java可以动态加载本机库,然后从它们调用方法。

For example, I'd like to do something like: 例如,我想做类似的事情:

int main() {
    libinfo_t * lib_details = load_shared_library("libfoo.so");
    run_method(lib_details, "bar", 7);
}

This would invoke the method 'bar' with argument 7 (bar is a method compiled into libfoo.so). 这将使用参数7调用方法'bar'(bar是编译为libfoo.so的方法)。

Use case details: 用例详细信息:

I'd like to compile a binary that loads all the shared libraries in a directory, and runs some method from each, in the memory context of the original program. 我想编译一个二进制文件,它加载目录中的所有共享库,并在原始程序的内存上下文中运行每个共享库的一些方法。 I'd like to be able to quickly enable or disable a shared library by adding/removing it from a directory. 我希望能够通过在目录中添加/删除共享库来快速启用或禁用它。

Proof of concept: 概念证明:

It seems this should be possible, based on the way java manages to link with jni code dynamically. 看来这应该是可能的,基于java设法动态链接jni代码的方式。 You can use System.load(), and load the library of your choice. 您可以使用System.load(),并加载您选择的库。 Coupled with compiling from memory, it seems it would allow you to run an arbitrary function from an arbitrary library. 再加上内存编译,似乎它允许你从任意库运行任意函数。 http://www.java2s.com/Code/Java/JDK-6/CompilingfromMemory.htm http://www.java2s.com/Code/Java/JDK-6/CompilingfromMemory.htm

Things I've tried: 我试过的事情:

  1. I've looked at the manpage for 'uselib', which seems useful, but I'm not sure what to do with the library once I've loaded it. 我已经查看了'uselib'的联机帮助页面,这看起来很有用,但是一旦我加载它,我不确定该如何处理它。

  2. A bit of googling returned http://dyncall.org/ , but this isn't exactly what I need -- this project still requires a function pointer to make the function call. 一些谷歌搜索返回http://dyncall.org/ ,但这不是我需要的 - 这个项目仍然需要一个函数指针来进行函数调用。

I'd be grateful for any pointer on where to look next, even without a concrete answer. 即使没有具体的答案,我也会感激任何指向下一步的指针。 Thanks! 谢谢!

Linux has a very complete API for this. Linux有一个非常完整的API。 It's the dlopen(3) API. 这是dlopen(3) API。

First, you call dlopen with a filename to get a shared library handle: 首先,使用文件名调用dlopen以获取共享库句柄:

void* lib = dlopen("./lib.so");

Than, to get a function pointer for a function in this library: 要获取此库中函数的函数指针:

int (*func)() = dlsym(lib, "thing");

Use this pointer as you please. 请随意使用此指针。

Finally, when you're done: 最后,当你完成时:

dlclose(lib)

Note: Remember to do error checking! 注意:记得做错误检查!

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM