我一直在試圖調用已在德爾福通過以下方式創建了一個方法:使用Delphi的stuct數組和字符串在C#中
function _Func1(arrParams: array of TParams): Integer;stdcall;
type
TParams = record
Type: int;
Name: string;
Amount : Real;
end;
我的代碼是:
[DllImport("some.dll", EntryPoint = "_Func1", CallingConvention = CallingConvention.StdCall)]
public static extern int Func(
[MarshalAs(UnmanagedType.LPArray, ArraySubType=UnmanagedType.Struct)] TParams[] arrParams)
而且該結構是:
[StructLayoutAttribute(LayoutKind.Sequential, CharSet = CharSet.Ansi)]
public struct TParams
{
public int Type;
[MarshalAs(UnmanagedType.AnsiBStr)]
public string Name;
public double Amount;
}
當我調用這個方法,我發現了錯誤: 無法編組場「名稱'類型'TParams':無效託管/非託管類型組合(字符串字段必須與LPStr,LPWStr,BStr或ByValTStr配對)。
但是沒有一個組合可以工作,因爲Delphi的字符串以它的長度作爲前綴並且當然是Ansi(我已經用其他字符串參數試過了)。有沒有人有線索如何解決這個問題?
感謝您的回答和編輯。我會嘗試這個解決方案。據我所知,我需要創建新的Delphi庫,將暴露使用字符串類型的函數,並將其替換爲PAnsiChar?那是對的嗎? – xurc
是的,這是正確的。魔鬼是在細節中,但在很高的層次上,你所說的是正確的。如果你這樣做,我可能會避開開放數組,並顯式地接收指向第一個元素和元素個數的指針。 –