大家好,我最近写的一个程序需要在线程单元中调用一个C++编写的动态链接库。我写了单独调用这个dll的exe程序,没有问题。但是在线程单元中调用这个动态库的时候,Exe大家好,我最近编写的一个程序需要在Delphi的线程单元中调用一个C++编写的动态链接库,在exe程序中我已经调用了这个动态库没有问题,但是在线程单元里调用这个动态库在Execute过程退出的时候出现一个access violation错误。好像是某个内存地址不可读。下面是我的线程单元的代码,请大家看一下,我第一次写这样的程序,写的可能有问题,请帮指点一下。谢谢。
procedure THLoginThread.Execute;
type
  //显示调用链接库
  tthauth_authenticate2userinfo_pin = function(serverip: PChar; serverport: Integer; appkey: PChar; user: PChar; pin: PChar; userinfo: p_userinfo): Integer; stdcall; //登录接口
var
  TpLogin: TFarProc;
  ILoginResult: Integer;
  pUserinfo: p_userinfo;
  Test: tthauth_authenticate2userinfo_pin;
begin
  { Place thread code here }
  EnterCriticalSection(OraCS); //进入临界区
  FreeOnTerminate := True;
  try
    Th := LoadLibrary('thauth.dll'); //加载动态链接库
    TpLogin := GetProcAddress(Th, 'thauth_authenticate2userinfo_pin');
    New(pUserinfo);
    @Test := TpLogin;
    if @Test <> nil then
      //断点调试过,就是下面这句话执行之后在退出这个过程的时候有问题,下面这句话执行通过了,返回值也对。
      ILoginResult := Test(PChar('166.111.4.125'), 3335, PChar('ICCARD:abcd1234'), PChar(Tid), PChar(Tpwd), pUserinfo);
    THLoginCheckResult := pUserinfo^.code;
    Dispose(pUserinfo);
    TpLogin := nil;
    FreeLibrary(Th);
  except
    THLoginCheckResult := -1;
  end;
  Synchronize(GiveResult);
  LeaveCriticalSection(OraCS); //退出临界区
end;

解决方案 »

  1.   

    TpLogin   :=   nil; TpLogin不需要赋值 把这句话注释掉看看TpLogin   :=   GetProcAddress(Th,   'thauth_authenticate2userinfo_pin '); FreeLibrary(Th); 会自动释放的
      

  2.   

    同一个DLL,在同一个应用程序当中不要多次LoadLibrary(多次也只加载一份)/FreeLibrary(由于多次只加载一份,从而导致Free可能存在问题,抱歉,本人没有进行过实测)。建议的办法是在线程当中Load之前如果必要的话,最好是复制一份存储为临时文件,虽然是同样代码的文件,但是实际文件不一样,就可以达到应用的效果了。