2014-05-11 44 views
1

這個任務很常見,我雖然很容易完成。但經過3個小時的谷歌搜索後,我放棄了。如何將字符串從VBA傳遞給Delphi DLL避免ShareMem使用?

我必須將字符串從MS Access VBA宏傳遞到Delphi DLL以使用Delphi DLL中的字符串進行操作。

環境:德爾福2010,Access 2010中

我也想避免使用ShareMem的。

我做什麼:

訪問:

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 

德爾福DLL:

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

至於結果,我有我的形式錯誤標題。 我應該修正什麼才能使它工作?

回答

2

我不確定你爲什麼試圖使用一個變體傳遞一個字符串。在我看來,傳遞字符串更合理。通過這樣做:

  1. 更改VBA Declare語句指定的參數類型爲ByVal par As String
  2. 將Delphi參數從PChar更改爲PAnsiChar。對於您的Unicode Delphi PCharPWideChar的別名。

另外,請注意Delphi export指令被忽略。你應該刪除它。

+0

感謝它爲我工作。 – mad

0

Delphi和VBA都支持變體。
在VBA中傳遞字符串作爲變體並在Delphi中將其作爲變體讀取應解決您的問題。

所以重新定義德爾福程序爲:

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

確保答:使用OleVariant,再也不回來(Ole)variant結果。
如果你想返回的結果做這樣的事情:

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

不要忘記ByVal在VBA來設置參數傳遞:

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

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

+1

如果您使用類似的變體,那麼當我使用OleVariant作爲輸入參數的類型時,VBA需要ByVal –

+0

我的Access實例崩潰。 – mad

+0

@mad這是因爲你在VBA上有ByRef,但是在Delphi方面通過了值。 –

相關問題