动态调用 DLL 中的函数

By definition DLLs are dynamically loaded libraries of functions and sometimes data. However, it's possible to either hard code the ability to "import" functions from DLLs or dynamically "bind" a DLL during the run time -- which of course means that we don't necessarily need to know the name of the DLL nor the name of the function we're about to call (to a certain extent) during the time we code. Dynamically loading and unloading DLLs could not only save memory, but also can help you write programs that are able to "adjust" itself if certain DLLs are missing.Following "LoadAndRunDLLProcedure()" function will let you pass the name of the DLL you want to connect to and the name of the function you want to call. If everything goes well, it will load the DLL, call the function, and then unload the DLL.

function LoadAndRunDLLProcedure(

  sDLL,

  sFunc : string )

  : boolean;

type

  // define the type of "function"

  // we're calling

  TFunc_Start = procedure;

var

  Func_Start : TFunc_Start;



  hDll       : THandle;

  FuncPtr    : TFarProc;

  sMsg       : string;

begin

  Result := False;

  hDll   := LoadLibrary(

              PChar( sDLL ) );

  if(hDll > 32)then

  begin

    FuncPtr :=

      GetProcAddress(

        hDll, PChar( sFunc ) );

    @Func_Start := FuncPtr;

    if(nil <> @Func_Start)then

    begin

      Func_Start;

      Result := True;

    end else

    begin

      sMsg := 'DLL entry point ' +

              sFunc + ' not found';

      MessageBox(

        0, PChar( sMsg ), 'Error',

        MB_OK );

    end;

    FreeLibrary( hDll );

  end else

  begin

    sMsg := 'File ' + sDLL +

            ' not found';

    MessageBox(

      0, PChar( sMsg ), 'Error',

      MB_OK );

  end;

end;





For example, let's say you want to call a procedure called "HelloWorld()"

in a DLL named "MyStuff.DLL:"



LoadAndRunDLLProcedure(

  'MyStuff.DLL',

  'HelloWorld' );





Please note that HelloWorld() must be a procedure, for example, declared as:

procedure HelloWorld;

or in C:

void HelloWorld();



  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值