Re: [問題] 動態載入一組函式

看板C_and_CPP作者 (purpose)時間13年前 (2012/02/24 17:50), 編輯推噓5(5010)
留言15則, 8人參與, 最新討論串3/3 (看更多)
※ 引述《james732 (好人超)》之銘言: : 假如我有這樣的一組介面: : class Calc : { : public: : virtual int add(int x, int y) = 0; : virtual int sub(int x, int y) = 0; : virtual int mul(int x, int y) = 0; : virtual int div(int x, int y) = 0; : }; : 我想問的是,有沒有辦法做到類似這樣的東西? : int main() : { : Calc *calc = NULL; : HANDLE hLibrary = Dynamic_Load("FastCalc.dll"); : calc = GetInterface(hLibrary); : calc->add(....); : calc->sub(....); : calc->mul(....); : calc->div(....); : return 0; : } : 也就是說,我有一個 pure virtual class 來描述介面 : 另外有個 FastCalc.dll 裡面實作了這個介面 (當然不管它是怎麼實作的) : 我想像上例這樣很簡單的載入整組介面來使用它 : 稍微研究過COM,不過還不是很熟,不知道它能不能做到這樣 : 如果可以的話請給我一些關鍵字或範例,COM對我來說實在不容易理解orz : 另外我也很好奇,在Linux環境有沒有辦法解決這個問題? : 話說,這個時候真的會很羨慕C#/Java的Reflection機制 XD 剛試了個方法,適用 VC + Windows 環境, 如下 ---- /* filename: calc.h */ struct calcFunctions { int (*myAdd)(int, int); int (*mySub)(int, int); }; ---- /* filename: foo.c compile with: cl.exe /LD foo.c */ #include "calc.h" #include <windows.h> int myAdd(int a, int b) { return a + b; } int mySub(int a, int b) { return a - b; } __declspec(dllexport) struct calcFunctions casio; BOOL WINAPI DllMain(HINSTANCE hinstDLL, DWORD fdwReason, LPVOID lpvReserved) { casio.myAdd = myAdd; casio.mySub = mySub; return TRUE; } ---- /* filename: test.c compile with: cl.exe test.c */ #include <windows.h> #include <stdio.h> #include "calc.h" int main() { struct calcFunctions* pCasio; HMODULE dll = LoadLibrary("foo.dll"); pCasio = (struct calcFunctions*) GetProcAddress(dll, "casio"); printf("add(12, 23) = %d\n", pCasio->myAdd(12, 23)); printf("sub(12, 23) = %d\n", pCasio->mySub(12, 23)); return 0; } ---- 輸出 D:\Desktop>test add(12, 23) = 35 sub(12, 23) = -11 ---- 可以不必用到 class,但 dll 寫起來麻煩。 -- ※ 發信站: 批踢踢實業坊(ptt.cc) ◆ From: 124.8.133.151

02/25 01:51, , 1F
原來getprocaddress可以不拿proc address而拿變數的addr
02/25 01:51, 1F

02/25 01:52, , 2F
ess 學到了 (筆記)
02/25 01:52, 2F

02/25 01:52, , 3F
還有記得calling convention也要統一 不能一下子cdecl
02/25 01:52, 3F

02/25 01:52, , 4F
一下子stdcall XD
02/25 01:52, 4F

02/25 02:02, , 5F
太深奧了..
02/25 02:02, 5F

02/25 02:08, , 6F
覺得好驚訝,我以為GetProcAddress只能拿function而已
02/25 02:08, 6F

02/25 02:23, , 7F
可能dll的symbol table本來就沒在分變數或function (嗎?
02/25 02:23, 7F

02/25 04:18, , 8F
02/25 04:18, 8F

02/25 05:33, , 9F
真的欸function or variable
02/25 05:33, 9F

02/25 05:34, , 10F
真的要學起來 (再度筆記)
02/25 05:34, 10F

02/25 06:20, , 11F
被發現沒有爬MSDN了...XDD
02/25 06:20, 11F

02/25 08:58, , 12F
這招好強阿~~~用 struct包func ptr再包成dll ...!!
02/25 08:58, 12F

02/25 12:42, , 13F
版主OS:超哥
02/25 12:42, 13F

02/25 13:25, , 14F
和l大的方法一樣都很讚:)
02/25 13:25, 14F

02/27 00:42, , 15F
這就是linux kernel內部使用的方式
02/27 00:42, 15F
請教一下前輩,出於何種目的,才讓 linux kernel 這麼做呢? 謝謝 ※ 編輯: purpose 來自: 124.8.145.239 (02/27 03:00)
文章代碼(AID): #1FHytLJq (C_and_CPP)
討論串 (同標題文章)
文章代碼(AID): #1FHytLJq (C_and_CPP)