dll中如何返回字符数组?(100)

  • 主题发起人 主题发起人 malloc
  • 开始时间 开始时间
M

malloc

Unregistered / Unconfirmed
GUEST, unregistred user!
我dll中的一个函数将要返回四个字符串,我考虑返回一个字符串数组, 请问dll中函数如何写。
 
type TArrStr=array [0..3] of shortString; //字符串如果可能长度超过255,就用String;函数:Procedure ProTest(ArrStr:TArrStr);
 
DLL为了在DELPHI中正常调用,必须用PCHAR
 
要不你的DLL输出一个类方法,然后调用DLL中的类,通过对象去调用方法。这样问题就比较简单。数组可以定义为DLL中类的类域。
 
library Project1;{ 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 SysUtils, Classes;function RetCharArray1:PChar;begin GetMem(result,255); StrCopy(result,'RetCharArray1');end;procedure RetCharArray2(vRet:PChar);begin StrCopy(vRet,'RetCharArray2');end;{$R *.res}exports RetCharArray1, RetCharArray2;beginend.//调用procedure TForm1.Button1Click(Sender: TObject);type TRetCharArray1=function:PChar; TRetCharArray2=procedure(vRet:PChar);var Call1:TRetCharArray1; Call2:TRetCharArray2; hDLL:THandle; p:PChar;begin if not FileExists('Project1.dll') then exit; hDLL:=LoadLibrary('Project1.dll'); try @Call1:=GetProcAddress(hDLL,'RetCharArray1'); if @Call1<>nil then edit1.Text:=Call1; GetMem(p,255); @Call2:=GetProcAddress(hDLL,'RetCharArray2'); if @Call2<>nil then begin Call2(p); edit2.Text:=p; FreeMem(p); end; finally if hDLL>0 then FreeLibrary(hDLL); end;end;最好用第二种方法,因为windows API函数大部分也是用参数返回字符数组,而不是直接以函数名的方式返回字符数组
 
你眼里只有字节流就行了。
 
你可以返回一个**P就可以了,但是这个内存需要在返回后手工去释放,或者你自己先Alloc一块内存,然后将该指针传给动态库,由动态库填写内容,最后释放,OK?
 
后退
顶部