DELPHI 求解DLL 返回 PCAHR 变量 问题

来源:百度知道 编辑:UC知道 时间:2024/07/04 11:35:18
function SRPL(sendbuf: string; sendlen: Integer; {ref string} var recvbuf: PAnsiChar; var recvlen: Integer; waitsecs: Integer): Integer; stdcall; External 'JEFLL.dll';

procedure TForm1.Button1Click(Sender: TObject);
var ll_recvlen, i: Integer;
ls_recvbuf: PAnsiChar;
ll_result: Integer;
ls_sendmsg, tmp: string;
begin
ll_recvlen := 6000;
try
ls_sendmsg := 'test';
ls_recvbuf := StrAlloc(6000);
ll_result := SRPL(ls_sendmsg, Length(ls_sendmsg), ls_recvbuf, ll_recvlen, 120);
if ll_result = 0 then //0表示执调用SRPL成功
begin
ShowMessage(ls_recvbuf); //执行相关返回PCHAR ls_recvbuf就会出错。。
end;
finally
StrDispose(ls_recvbuf);
end;
end;

哪位大哥知道原因。。。。
procedure TForm1.Button1Click(Sender: TObject);
var ll_recvlen, i: Integer;
ls_recvbuf: PAnsiChar;
ll_result: Integer;
ls_sendmsg, tmp: string;
begin

如果你的function SRPL是在DLL中定义的,这样写肯定错了,不能使用string,除非在程序中添加ShareMem 并附带一个BORLNDMM.DLL文件,在新建立的DLL文件的unit中有说明的:
{ 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. }

不想这么复杂,把string全部改成PCHAR就可以很简单的解决了。

我看到有两点问题,你修正一下看能不能解决。
1。对资源的请求 stralloc应该放到try..finally..end结构的外面去。在这个程序里看起来问题不大。
2。 对Buffer请求的空间大小应该是你传输数据大小+1,不要忘了后面还有一个#0需要保存。