Charles Parker
2003-08-20 14:05:59 UTC
I have a COM object that allocates and passes back a pointer to an array of
DATA_MAP structures. A test app written in C++ work correctly however a C#
.NET app returns garbage. In .NET the managed structure is defined as:
[StructLayout(LayoutKind.Sequential)]
public struct DATA_MAP
{
[MarshalAs(UnmanagedType.ByValTStr, SizeConst=65)]
public string szRegDB;
[MarshalAs(UnmanagedType.ByValTStr, SizeConst=65)]
public string szTableName;
[MarshalAs(UnmanagedType.ByValTStr, SizeConst=65)]
public string szColumnName;
public int iRestrictAccess;
[MarshalAs(UnmanagedType.ByValTStr, SizeConst=1024)]
public string szRestrictionText;
}
The code to retrieve the data is shown below:
// Retrieve the records
IntPtr buffer = Marshal.AllocCoTaskMem(Marshal.SizeOf(typeof(DATA_MAP)) *
iRecordsReturned);
IData.GetDataAttr(sUserName, sbEncodedPwd.ToString(), iAppID, iConnectType,
iRecordsReturned, buffer);
pDataMapOut = new DATA_MAP[iRecordsReturned];
IntPtr iter = buffer;
for (int i=0; i<iRecordsReturned; i++)
{
pDataMapOut[i] = (DATA_MAP)Marshal.PtrToStructure(iter,
typeof(DATA_MAP));
iter = (IntPtr)((int)iter + Marshal.SizeOf(typeof(DATA_MAP)));
}
The first string in the returned structure is garbage while the remaing
strings are empty/blank. Debugging through the COM object data in the array
of structures is correct so the problem must be in the marshalling to the
managed structure. Any ideas on how to solve this problem would be greatly
appreciated. Thanks.
Charles...
DATA_MAP structures. A test app written in C++ work correctly however a C#
.NET app returns garbage. In .NET the managed structure is defined as:
[StructLayout(LayoutKind.Sequential)]
public struct DATA_MAP
{
[MarshalAs(UnmanagedType.ByValTStr, SizeConst=65)]
public string szRegDB;
[MarshalAs(UnmanagedType.ByValTStr, SizeConst=65)]
public string szTableName;
[MarshalAs(UnmanagedType.ByValTStr, SizeConst=65)]
public string szColumnName;
public int iRestrictAccess;
[MarshalAs(UnmanagedType.ByValTStr, SizeConst=1024)]
public string szRestrictionText;
}
The code to retrieve the data is shown below:
// Retrieve the records
IntPtr buffer = Marshal.AllocCoTaskMem(Marshal.SizeOf(typeof(DATA_MAP)) *
iRecordsReturned);
IData.GetDataAttr(sUserName, sbEncodedPwd.ToString(), iAppID, iConnectType,
iRecordsReturned, buffer);
pDataMapOut = new DATA_MAP[iRecordsReturned];
IntPtr iter = buffer;
for (int i=0; i<iRecordsReturned; i++)
{
pDataMapOut[i] = (DATA_MAP)Marshal.PtrToStructure(iter,
typeof(DATA_MAP));
iter = (IntPtr)((int)iter + Marshal.SizeOf(typeof(DATA_MAP)));
}
The first string in the returned structure is garbage while the remaing
strings are empty/blank. Debugging through the COM object data in the array
of structures is correct so the problem must be in the marshalling to the
managed structure. Any ideas on how to solve this problem would be greatly
appreciated. Thanks.
Charles...