【发布时间】:2011-11-23 21:19:08
【问题描述】:
又一个 Delphi 互操作问题......
我有这个 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 结构数组更改为使用简单的整数数组,一切都很好。
为什么整数数组有效,而结构数组却无效?
【问题讨论】: