Delphi 将字符串参数传递给IDispatch.Invoke

vxf3dgd4  于 2022-11-04  发布在  其他
关注(0)|答案(1)|浏览(115)

使用 Delphi 11.1,我想使用IActiveScript添加脚本到我的应用程序中。我创建了一个小的VBScript来测试从Delphi到Script的参数传递:

function test2(n)
  MsgBox n
  test2 = n
end function

VBScript代码加载正常,传递一个整数作为参数工作正常,但当传递一个字符串参数时,我发现只有字符串的前半部分进入脚本。 Delphi 代码:

procedure TForm1.Button4Click(Sender: TObject);
var
  Disp: IDispatch;
  Res: OleVariant;
  DispParams: TDispParams;
  s: string;
  n: Integer;
  v: Variant;
  Arg: array of TVariantArg;
begin
  OleCheck(FScript.GetScriptDispatch(nil, Disp));

  s := 'test2';

  OleCheck(Disp.GetIDsOfNames(GUID_NULL, @s, 1, 1033, @n));

  v := VarArrayOf(['1234567890']);

  SetLength(Arg, VarArrayHighBound(v, 1) - VarArrayLowBound(v, 1) + 1);

  arg[0].vt := VT_BSTR;
  arg[0].bstrVal := PWideChar(VarToStr(v[0])); //passes first half of string only
//  arg[0].bstrVal := SysAllocString(PWideChar(VarToStr(v[0]))); //passes complete (copy of) string
  end;

  DispParams.rgvarg := @Arg[0];
  DispParams.rgdispidNamedArgs := nil;
  DispParams.cArgs := 1;
  DispParams.cNamedArgs := 0;
//at this point, debugger shows no difference, bstrVal holds full string
  OleCheck(Disp.Invoke(n, GUID_NULL, 1033, DISPATCH_METHOD, DispParams, @res, nil, nil));
end;

MsgBox显示12345。已尝试其他字符串,其他字符串长度也是如此,始终仅前半部分。
有谁能帮我解释一下吗?

uyhoqukh

uyhoqukh1#

当与COM接口时,需要使用WideString(COM BSTR字符串的 Package )而不是使用string(也称为UnicodeString),例如:

procedure TForm1.Button4Click(Sender: TObject);
var
  Disp: IDispatch;
  Res: OleVariant;
  DispParams: TDispParams;
  s: WideString;
  n: Integer;
  v: Variant;
  Arg: array of TVariantArg;
begin
  OleCheck(FScript.GetScriptDispatch(nil, Disp));

  s := 'test2';
  OleCheck(Disp.GetIDsOfNames(GUID_NULL, @s, 1, 1033, @n));

  v := VarArrayOf(['1234567890']);

  SetLength(Arg, VarArrayHighBound(v, 1) - VarArrayLowBound(v, 1) + 1);

  s := VarToWideStr(v[0]);
  arg[0].vt := VT_BSTR;
  arg[0].bstrVal := PWideChar(s);
  //arg[0].bstrVal := SysAllocString(PWideChar(s));

  DispParams.rgvarg := @Arg[0];
  DispParams.rgdispidNamedArgs := nil;
  DispParams.cArgs := 1;
  DispParams.cNamedArgs := 0;

  OleCheck(Disp.Invoke(n, GUID_NULL, 1033, DISPATCH_METHOD, DispParams, @res, nil, nil));

  //SysFreeString(arg[0].bstrVal);
end;

相关问题