【发布时间】:2011-11-13 01:53:26
【问题描述】:
我有一个包含以下类型的 Delphi DLL:
type
TStepModeType = (smSingle, smMultiStep);
TParameter = record
Number: Integer;
end;
TStruct = record
ModType: PAnsiChar;
ModTypeRev: Integer;
ModTypeID: Integer;
RecipeName: PAnsiChar;
RecipeID: Double;
RootParamCount: Integer;
StepMode: TStepModeType;
ParamCount: Integer;
Parameters: array of TParameter;
end;
我需要从 C# 调用这个 DLL,传递一个与 DLL 将填充和返回的 Delphi 类型相对应的 ref 对象。我在我的 C# 代码中定义了这样的结构:
enum stepModeType
{
Single,
MultiStep
}
[StructLayout(LayoutKind.Sequential)]
struct parameter
{
public int Number;
}
[StructLayout(LayoutKind.Sequential)]
struct recipe
{
public string modType;
public int modTypeRev;
public int modTypeId;
public string recipeName;
public double recipeId;
public int rootParamCount;
public stepModeType stepMode;
public int paramCount;
public IntPtr parameters;
}
在遇到 Delphi 代码中的动态数组(参数:TParameter 数组)之前,我做得很好。我知道动态数组是 Delphi 唯一的构造,所以我选择在我的 C# 代码中使用 IntPtr 以希望获得指向数组的指针并提取内容。不幸的是,我对这个互操作的东西相当陌生,我不知道如何处理 IntPtr。
假设 Delphi DLL 使用 2 个参数项填充动态数组。一旦从 Delphi DLL 传递回我的 C# 调用应用程序,有人可以向我展示 C# 代码,该代码会将这两个参数项从数组中取出吗?
更新:好吧,碰巧我得到的 Delphi 代码是一个简化版本。我们的一位 Delphi 开发人员认为简化版本比实际版本更容易上手,实际版本包含动态数组的动态数组的动态数组要复杂得多。无论如何,我现在完全超出了我的头脑。我只知道德尔福是危险的。下面是 Delphi 代码中真实结构的代码。任何有关如何从我的 C# 调用应用程序处理这些结构的进一步指导将不胜感激。动态数组的嵌套甚至是不可能的。
type
TStepModeType = (smSingle, smMultiStep);
TParamValue = record
strVal: String;
fVal: Double;
Changed: Boolean;
end;
TSteps = array of TParamValue;
TRule = record
Value: String;
TargetEnabled: Boolean;
end;
TParamInfo = record
Caption: String;
Units: String;
RuleCount: Integer;
Rules: array of TRule;
end;
TParameter = record
Info: TParamInfo;
Steps: TSteps;
end;
TStruct = record
ModType: PAnsiChar;
ModTypeRev: Integer;
ModTypeID: Integer;
RecipeName: PAnsiChar;
RecipeID: Double;
RootParamCount: Integer;
StepMode: TStepModeType;
ParamCount: Integer;
Parameters: array of TParameter;
end;
【问题讨论】:
-
Delphi DLL 是否包含释放结构中动态内存的函数?
-
确实如此,但正如您在回答中指出的那样,我仍在错误地使用字符串字段,这会导致内存问题。