Question

the task is very common and I though it is very easy to complete. But after 3 hours of googling I have gave up.

I have to pass string from MS Access VBA macros to Delphi DLL to operate with the string inside Delphi DLL.

Enviroment: Delphi 2010, Access 2010

I also want to avoid using of ShareMem.

What I do:

Access:

Option Compare Database

Private Declare Function callForm Lib "C:\Programing\_contract\MyWork_2014\AccessDLL\build\access.dll" (ByRef par As Variant) As Long

Private Sub Button0_Click()
    MsgBox callForm("alex")
End Sub

Delphi DLL:

function callForm(par: PChar): Integer; export; stdcall;
var
  buf: PWideChar;
  s: String;
  rs: RawByteString;
begin
  frmAccessTest.Caption := par;
  frmAccessTest.ShowModal;
  Result := 456;
end;

As result I have wrong caption of my form. What should I fix to get it working?

Was it helpful?

Solution

I'm not sure why you attempted to use a variant to pass a string. It seems to me to be more sensible to pass a string. Do this by:

  1. Changing the VBA Declare statement to specify the parameter type to be ByVal par As String.
  2. Changing the Delphi parameter from PChar to PAnsiChar. For your Unicode Delphi PChar is an alias to PWideChar.

As an aside, do note that the Delphi export directive is ignored. You should remove it.

OTHER TIPS

Both Delphi and VBA support variants.
Passing the string as a variant in VBA and reading it as a variant in Delphi should solve your problem.

So redefine the Delphi routine as:

function callForm(par: Olevariant): Integer; stdcall;
begin
  frmAccessTest.Caption := par;
  frmAccessTest.ShowModal;
  Result := 456;
end;

Make sure to A: use OleVariant and never return (Ole)variant as a result.
If you want to return a result do something like:

procedure ReturnAString(A: integer; out B: OleVariant); stdcall;

Don't forget to set the parameter passing by ByVal in VBA:

Private Declare Function callForm Lib "path.dll" (ByVal par As Variant) As Long

See also: How do I (or if I can't) use Variants on simple DLLs?

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top