【发布时间】:2014-09-17 10:52:09
【问题描述】:
我正在尝试在 Delphi 中编写一个 DLL,以允许我的 C# 应用程序访问 Advantage 数据库(使用 VS2013 并且无法直接访问数据)。
我的问题是调用后,C# 中的数组充满了空值。
Delphi DLL 代码:
TItem = record
Id : Int32;
Description : PWideChar;
end;
function GetNumElements(const ATableName: PWideChar): Integer; stdcall;
var recordCount : Integer;
begin
... // code to get the number of records from ATableName
Result := recordCount;
end;
procedure GetTableData(const ATableName: PWideChar; const AIdField: PWideChar;
const ADataField: PWideChar; result: array of TItem); stdcall;
begin
... // ATableName, AIdField, and ADataField are used to query the specific table, then I loop through the records and add each one to result array
index := -1;
while not Query.Eof do begin
Inc(index);
result[index].Id := Query.FieldByName(AIdField).AsInteger;
result[index].Description := PWideChar(Query.FieldByName(ADataField).AsString);
Query.Next;
end;
... // cleanup stuff (freeing created objects, etc)
end;
这似乎有效。我已经使用 ShowMessage 来显示输入的信息是什么样的以及之后的样子。
C# 代码:
[StructLayoutAttribute(LayoutKind.Explicit)] // also tried LayoutKind.Sequential without FieldOffset
public struct TItem
{
[FieldOffset(0)]
public Int32 Id;
[MarshalAs(UnmanagedType.LPWStr),FieldOffset(sizeof(Int32))]
public string Description;
}
public static extern void GetTableData(
[MarshalAs(UnmanagedType.LPWStr)] string tableName,
[MarshalAs(UnmanagedType.LPWStr)] string idField,
[MarshalAs(UnmanagedType.LPWStr)] string dataField,
[MarshalAs(UnmanagedType.LPArray)] TItem[] items, int high);
public void GetListItems()
{
int numProjects = GetNumElements("Project");
TItems[] projectItems = new TItem[numProjects];
GetTableData("Project", "ProjectId", "ProjectName", projectItems, numProjects);
}
此代码执行,没有任何错误,但是当我遍历 projectItems 时,每个都返回
Id = 0
Description = null
【问题讨论】:
标签: c# delphi pinvoke delphi-xe3