先制作個簡單的動態鏈接庫,再在Qt里面加載它。
【制作動態鏈接庫】
先編寫一個hello.c
1 #
2 ()3 {4 ("hello world!\n");5 }
在Linux下編譯,生成hello.o:
gcc -c hello.c
編譯成動態鏈接庫.so(注意:Linux下的動態鏈接庫以lib開始命名):
gcc - -o .so hello.o
【加載動態鏈接庫】
在Qt中加載.solinux 指定動態連接庫,先創建一個空的Qt工程,添加新文件main.c,內容如下:
1 #
2 #
3
4 int main(int argc, char *argv[])5 {6 * =NULL;7 //寫清楚庫的路徑linux 指定動態連接庫,如果放在當前工程的目錄下,路徑為./.so
8 = new ("/home/.so");9
10 //加載動態庫
11 ->load();12 if (!->())13 {14 ("load .so !\n");15 0;16 }17
18 //定義函數指針
19 void (*Fun)();20
21 //得到庫中函數地址
22 Fun hello = (Fun)->("hello");23 if(hello)24 {25 hello();26 }27
28 //卸載庫
29 ->();30 0;31 }
運行后輸出:hello world!
還有一種方法:主程序在編譯的時候加上-L. -.so
【的文檔】
The class loads at .
An of a on a file (which we call a "", but is also known as a "DLL"). A to the in the in a way. You can pass a file name in the , or set it with (). When the , in all the - (e.g. on Unix), the file name has an path. If the file be found, tries the name with - file , like ".so" on Unix, ".dylib" on the Mac, or ".dll" on and . This makes it to that are only by their (i.e. their ), so the same code will work on .
The most () to load the file, () to check was , and () to a in the . The () tries to load the if it has not been yet. of can be used to the same . Once , in until the . You can to a using (), but if other of are using the same , the call will fail, and will only when every has ().
A use of is to an in a , and to call the C that this . This is " " in to " ", which is done by the link step in the build when an a .
Note: In using their names is only if the is built as . must be used. Also, in the path of the is and is used.
The code loads a , the "", and calls the if . If goes wrong, e.g. the file does not exist or the is not , the will be 0 and won't be .
myLib("mylib");
(*)();
= () myLib.("");if()
();
The must be as a C from the for () to work. This means that the must be in an "C" block if the is with a C++ . On , this also the use of a macro; see () for the of how this is done. For , there is a () which you can use if you just want to call a in a the first:
void (*)();
= () ::("mylib", "");if()
();
【參考文獻】