简体   繁体   中英

How to execute some function in a shared library

I'm wondering how can a program "recoglize" some function in some executable or shared library if they're not compiled together. I know that sounds confusing, here's a much detailed explaination:

Suppose I have a program called "A". Now I want to put some additional compiled shared library "B" in some specified location so that "A" can run function in it, without changing the code of A itself. Of course I can use also some additional file like txt file, and of course the source code is visible. How should I design the whole system so that it can work?

If you think about it as a game, EG a card game, here is the situation. You have the game, and you insist on writing purely C++ (so you have to compile everything). Now you already have the publised game. But some DIYer want to add some new card to the game (they can't change the executable itself since what if there are more that one DIY?). You can do the card data part by txt or db or whatever, but for the "effect" part, you have to code and compile them to something. How should the main program call the card "effect" function in compiled library?

And by the way I know I can do it with sript language like LUA or whatever, but what if I want to do it "the compiled way"?

Here is the more specific example:

A.cpp: int main(){ FuncA(); FuncB(); FuncC(); ... } // and something else

B.cpp: int TheFunction(){ .... } // that's it

The program don't know the existence of "B", but it is designed so that if I can compile B to some kind of B.so, and put it in a specified folder, "A" can execute the TheFunction()

I know that sound really wield, but here is what I am thinking about:

When compiling B, use some way to have the compiler generate some kind of function pointer list to a txt file. And the program A reads that file, and runs the function the pointer points to in B.

Is that possible? Or there's something I actually understood wrong?

Dynamic linking is not something that's covered by the C++ standard so how this works is implementation dependent. On Windows for example you would build a DLL and then load it dynamically using LoadLibrary() and get a pointer to the function you want to call using GetProcAddress() . Other platforms offer similar functionality using different APIs.

Of course C++ is a statically compiled language so you need to know the signature of a function before you can call it. Your program will have to define some standard function interface for 'plugins' to implement in DLLs in order to be able to call into code that is written after the original program is built.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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