开发者

Calling a function in a shared library given its name and signature

I have a little DSL that needs to be able to load shared libraries and run functions that they export. Finally, a solved problem: dlopen, dlsym, LoadLibrary, and GetProcAddress are all you need for cross-platform use of dynamic libraries. This is easy!

C++ disagrees.

Thanks to dlsym, etc., I've got everything I need: a开发者_运维百科 function pointer from the library, a representation of a signature from the source file, and…no way to call one using the other.

I just want to confirm my thinking that no amount of trickery with varargs, variadic templates, or other wizardry is going to help if all the type information I have is dynamic. I'll be going with one of the following solutions, and would also like opinions on which is preferable (I'm leaning toward the latter).

  • Restrict the signature to accepting and returning a marshalled object pointer, and write a wrapper for every library with which the language will be used.

  • Compile the DSL to a C-compatible language (read: C++) so that the requisite information is available at compile-time (read: second compile time).


Use libffi to call the function. If you have a pointer to the function, and you know its argument & return types, you're golden. Ffi knows how to deal with the platform-specific ABI, building the stack frame, pushing the arguments and popping the return value, etc.

C++ name-mangling makes this a bit more difficult, but if you've already managed to get a function pointer, it sounds like you have that part solved already...

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜