用C允许动态加载库"发布]使用功能 [英] Allowing dynamically loaded libraries in C to "publish" functions for use

查看:118
本文介绍了用C允许动态加载库"发布]使用功能的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我C语言编写一个程序,它允许用户实现自定义功能由各种各样的跨preTER运行。我也想允许用户在普通的C写这些自定义函数,然后在动态加载。为了做到这一点,我创建了两个结构,一个用于除preTED功能,一个是本地的。

I'm writing a program in C which allows users to implement custom "functions" to be run by an interpreter of sorts. I also want to allow users to write these custom functions in plain C, and then be loaded in dynamically. In order to do this, I created two structs, one for interpreted functions, and one for native ones.

下面是一个简单的例子:

Here's a simplified example:

struct func_lang {
    bool is_native;
    char* identifier;
    // various other properties
}

typedef void (*func_native_ptr)(int);
struct func_native {
    bool is_native;
    char* identifier;
    func_native_ptr func_ptr;
}

然后我用每个结构的标识符属性,把它们放在一个哈希表,我就可以使用在运行时执行。

I then use the identifier property of each struct to put them in a hashtable, which I can then use to execute them at runtime.

我的问题实际上是从另一端的加载库。我希望能够让装库发布,其功能他们想要插入到列表中。例如,也许有这样的功能:

My problem is actually from the other end, the loaded libraries. I'd like to be able to allow the loaded libraries to "publish" which functions they want inserted into the list. For example, maybe with a function like this:

void register_func_native(char* identifer, func_native_ptr func_ptr);

然后,当我想从库调用的init 功能,他们可以调用这个函数来将函数插入哈希表。

Then, when I would call an init function from the library, they could call this function to insert the functions into the hashtable.

将这项工作?我有点困惑的 register_func_native 功能将如何联系在一起,因为它是由加载库需要的,但必须由加载程序本身来定义。请问我的加载函数需要另一个共享库,然后可以在运行时被链接到实现?

Will this work? I'm a little confused about how the register_func_native function would be linked, since it's needed by the loaded library, but would have to be defined by the loader itself. Does my loader function need to be implemented in another shared library, which could then be linked at runtime?

推荐答案

这将取决于平台上,但Linux和所有的Unix我所看到的,这将工作。例如:

This will depend on the platform, but on Linux and all the Unixes I've seen, this will work. Example:

$ cat dll.c
void print(char const *);

void foo()
{
    print("Hello!");
}
$ gcc -Wall -shared -fPIC -o dll.so dll.c
$ cat main.c
#include <dlfcn.h>
#include <stdio.h>

void print(char const *msg)
{
    puts(msg);
}

int main()
{
    void *lib = dlopen("./dll.so", RTLD_NOW);
    void (*foo)() = (void (*)())dlsym(lib, "foo");
    foo();
    return 0;
}
$ cc -fPIC -rdynamic main.c -ldl
$ ./a.out 
Hello!

这篇关于用C允许动态加载库&QUOT;发布]使用功能的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆