我想做一个dll,这个dll必须给我返回一个字符串,
怎样实现?谢谢!

解决方案 »

  1.   

    直接返回PChar不就行了?只是要注意该对象的生存期问题
      

  2.   

    使用Sharemem单元,Dll工程文件以及调用该Dll的工程文件都要引用这个单元
      

  3.   

    library OfficeDir;function getOfficeDir: PChar; stdcall;
    const
      c_Reg = '\SOFTWARE\Microsoft\Office';
      c_Excel = 'Excel';
      c_InstallRoot = 'InstallRoot';
      c_Path = 'Path';
    var
      RegOffice: TRegistry;
      slSubOfficeKeys: TStringList;
      slSubSubKeys: TStringList;
      I: Integer;
      sReturn: PChar;
      sSubKey: string;
      iIndex: Integer;
      sKey: string;
    begin
      //FillChar(sReturn, 50, #0);
      RegOffice := TRegistry.Create;
      try
        slSubOfficeKeys := TStringList.Create;
        slSubSubKeys := TStringList.Create;
        try
          RegOffice.RootKey := HKEY_LOCAL_MACHINE;
          if RegOffice.OpenKey(c_Reg, False) then
          begin
            try
              RegOffice.GetKeyNames(slSubOfficeKeys);
              for I := 0 to slSubOfficeKeys.Count - 1 do
              begin
                sSubKey := c_Reg + '\' + slSubOfficeKeys[I];
                if RegOffice.OpenKey(sSubKey, False) then
                begin
                  RegOffice.GetKeyNames(slSubSubKeys);
                  iIndex := slSubSubKeys.IndexOf(c_Excel);
                  if iIndex < 0 then
                    Continue;
                  sSubKey := sSubKey + '\' + c_Excel + '\' + c_InstallRoot;
                  if RegOffice.OpenKey(sSubKey, False) then
                  begin
                    sKey := RegOffice.ReadString(c_Path);
                   sReturn := PChar(sKey);
                  end;
                  Break;
                end;
              end;
            finally
              RegOffice.CloseKey;
            end;
          end;
        finally
          FreeAndNil(slSubOfficeKeys);
          FreeAndNil(slSubSubKeys);
        end;
      finally
        result := sReturn;
        FreeAndNil(RegOffice);
      end;
    end;
    exports
      getOfficeDir;end.
      

  4.   

    前面还应该有这些:library OfficeDir;{ Important note about DLL memory management: ShareMem must be the
      first unit in your library's USES clause AND your project's (select
      Project-View Source) USES clause if your DLL exports any procedures or
      functions that pass strings as parameters or function results. This
      applies to all strings passed to and from your DLL--even those that
      are nested in records and classes. ShareMem is the interface unit to
      the BORLNDMM.DLL shared memory manager, which must be deployed along
      with your DLL. To avoid using BORLNDMM.DLL, pass string information
      using PChar or ShortString parameters. }uses
      ShareMem,
      SysUtils,
      Classes, Windows, Registry;{$R *.res}
      

  5.   

    同意楼上在调用DLL的函数时,
    先给实参分配内存,然后传递此参数给DLL的函数中的PChar类型的形参,
    实参使用完毕不要忘了释放它的内存