union marshalling issue in C#
- by senthil
I have union inside structure and the structure looks like
struct tDeviceProperty {
DWORD Tag;
DWORD Size;
union _DP value;
};
typedef union _DP
{
short int i;
LONG l;
ULONG ul;
float flt;
double dbl;
BOOL b;
double at;
FILETIME ft;
LPSTR lpszA;
LPWSTR lpszW;
LARGE_INTEGER li;
struct tBinary bin;
BYTE reserved[40];
} __UDP;
struct tBinary {
ULONG size;
BYTE * bin;
};
from the tBinary structure bin has to be converted to tImage (structure is given below)
struct tImage {
DWORD x;
DWORD y;
DWORD z;
DWORD Resolution;
DWORD type;
DWORD ID;
diccid_t SourceID;
const void *buffer;
const char *Info;
const char *UserImageID;
};
to use the same in c# I have done marshaling but not giving proper values when converting the pointer to structure. The C# code is follows,
tBinary tBin = new tBinary();
IntPtr tBinbuffer = Marshal.AllocCoTaskMem(Marshal.SizeOf(tBin));
Marshal.StructureToPtr(tBin.bin, tBinbuffer, false);
tDeviceProperty tDevice = new tDeviceProperty();
tDevice.bin = tBinbuffer;
IntPtr tDevicebuffer = Marshal.AllocCoTaskMem(Marshal.SizeOf(tDevice));
Marshal.StructureToPtr(tDevice.bin, tDevicebuffer, false);
Battary tbatt = new Battary();
tbatt.value = tDevicebuffer;
IntPtr tbattbuffer = Marshal.AllocCoTaskMem(Marshal.SizeOf(tbatt));
Marshal.StructureToPtr(tbatt.value, tbattbuffer, false);
result = GetDeviceProperty(ref tbattbuffer);
Battary v = (Battary)Marshal.PtrToStructure(tbattbuffer, typeof(Battary));
tDeviceProperty v2 = (tDeviceProperty)Marshal.PtrToStructure(tDevicebuffer, typeof(tDeviceProperty));
tBinary v3 = (tBinary)Marshal.PtrToStructure(tBinbuffer, typeof(tBinary));