另一個德爾福互操作問題中返回結構......C#調用DLL德爾福該結構
我有這樣的Delphi代碼:
library DelphiDll;
uses
Dialogs,
SysUtils,
Classes;
type
TestEnum = (teOne, teTwo);
TTestRecord = record
end;
TTestType = record
MyTestRecords: array [1..255] of TTestRecord;
MyTestEnum: TestEnum;
end;
{$R *.res}
function DllFunction(var testType: TTestType): Boolean stdcall; export;
begin
testType.MyTestEnum := teTwo;
Result := True;
end;
exports DllFunction;
begin
end.
而這個C#代碼:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Runtime.InteropServices;
namespace DelpiDllTester
{
public enum TestEnum
{
One,
Two
}
[StructLayout(LayoutKind.Sequential)]
public struct TestType
{
[MarshalAs(UnmanagedType.ByValArray, SizeConst = 255)]
public TestRecord[] MyTestRecords;
public TestEnum MyTestEnum;
}
[StructLayout(LayoutKind.Sequential)]
public struct TestRecord
{
}
class Program
{
[DllImport("DelphiDll.dll", CallingConvention = CallingConvention.StdCall, CharSet = CharSet.Ansi)]
public static extern bool DllFunction(ref TestType testType);
static void Main(string[] args)
{
TestType testType = new TestType();
bool dllFunctionResult = DllFunction(ref testType);
Console.WriteLine(dllFunctionResult);
Console.WriteLine(testType.MyTestEnum);
Console.ReadLine();
}
}
}
當我運行C#代碼時,testType.MyTestEnum的控制檯輸出始終是枚舉值One,即使它在Delphi代碼中明確設置爲Two。
現在,如果我只是簡單地將TestType結構中的TestRecord結構數組改爲使用簡單的整數數組,那麼一切都很好。
爲什麼整數數組工作,但結構數組沒有?
Doh!你曾經有過這樣的一段時間,你只是陷入了一種思考,似乎無法擺脫。我提供的代碼是真實代碼的一個修剪過的示例,但我沒有注意到這樣一個事實,即我的裁剪代碼和空記錄會導致這樣的問題。再次感謝所有的評論。下次我會更加關注。 – meyousikmann