另一个德尔福互操作问题中返回结构......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