如何才能封装在Dll中的过程的可变参数返回值?

hxf812 2001-09-01 10:14:14
如何才能封装在Dll中的过程的可变参数返回值?

小弟用d5写了个动态连接库,用到了可变参数,我希望通过多个可变参数返回处理结果,我用D5可以调用,用Vb调用失败,
代码如下
//D5 Dll
...
procedure Test(var S1,S2 : PChar);stdcall;
begin
S1 := 'dll string1';
S2 := 'dll string2';
end;

{$R *.RES}
exports Test;
..

//D5调用 Test 的例子
procedure Test(var S1,S2: PChar); stdcall; external 'E:\Borland\Delphi5\Projects\DllDemo\Dll\Project1.dll';//声明

procedure TForm1.Button1Click(Sender: TObject);
var
S1,S2 : PChar;
begin
try
try
S1 := StrAlloc(100);
S2 := StrAlloc(100);
Test(S1,S2);
ShowMessage(Format('S1 = %s S2 = %s',[S1,S2]));
except
end; //except
finally
{
StrDispose(S1); (********)
StrDispose(S2); (********)
}
end; //finally

end;

//VB调用 Test 过程的例子
Public Declare Sub Test Lib "E:\Borland\Delphi5\Projects\DllDemo\Dll\Project1.dll" (ByRef S1 As String, ByRef S2 As String)//模块中的声名

//VB 调用
Private Sub Command1_Click()
Dim S1 As String
Dim S2 As String
S1 = ""
S2 = ""
Test S1, S2
MsgBox "S1 = " & S1 & Chr(10) & Chr(13) & "S2 = " & S2
End Sub

D5可以调用,VB不能调用,why? 我哪写错了吗?
还有,(********)标记的地方为什么一执行就出错, StrDispose调用FreeMem释放PChar的资源,
这是我粘的 SysUtils单元的代码
procedure StrDispose(Str: PChar);
begin
if Str <> nil then
begin
Dec(Str, SizeOf(Cardinal));
FreeMem(Str, Cardinal(Pointer(Str)^));
end;
end;
我该如何才能释放为 Pchar 分配的资源

还请各位大虾多多指点。谢谢!如果分数太少还可以再加。
...全文
107 5 打赏 收藏 转发到动态 举报
写回复
用AI写文章
5 条回复
切换为时间正序
请发表友善的回复…
发表回复
chechy 2001-09-01
  • 打赏
  • 举报
回复
不分配内存也可以。因为是直接赋值啊。
Nicrosoft 2001-09-01
  • 打赏
  • 举报
回复
s1所占内存空间是不定的,s1=""时,不占用内存,因此内存使用非法。
hxf812 2001-09-01
  • 打赏
  • 举报
回复
多谢chechy(chechy)和to Nicrosoft(奈软)两位大虾,问题解决。
小弟还有两个问题
1。to 奈软:为什么一定要传一个定长定长字符串。
2。to chechy:那我用D5向Test传参数时如何为pchar变量分配内存?如何释放呢?
Nicrosoft 2001-09-01
  • 打赏
  • 举报
回复
vb代码改成
dim s1 as string *100
dim s2 as string *100
chechy 2001-09-01
  • 打赏
  • 举报
回复
Delphi的问题很容易解释。实际上StrAlloc(100);这句是无效的。
因为DLL中的代码是直接赋值,也就是说string实际上是指向'dll string1'的地址,而不是StrAlloc的地址。如果想使用StrAlloc的地址,我想应该这样:
StrPCopy(s1, 'dll string1');
StrPCopy(s2, 'dll string2');
这样StrDispose应该没有问题,否则StrAlloc和StrDispose都不需要。
VB没用过,不知道,不过我猜想:
StrPCopy(s1, 'dll string1');可能没有问题。

5,386

社区成员

发帖
与我相关
我的任务
社区描述
Delphi 开发及应用
社区管理员
  • VCL组件开发及应用社区
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
暂无公告

试试用AI创作助手写篇文章吧