tags:

views:

180

answers:

1

I have a C++ structure, and I have to interop it from my C# code.

I compile my C# code as a platform agnostic dll, which means that I can use the same C# dll on different platforms ( 32bit or 64bit-- doesn't matter), whereas I distribute the C++ differently for different platforms.

The problem is that the C++ structure that I must interop seems to work for different C# definition. In 64 bit OS, the following structure works:

    [StructLayout(LayoutKind.Sequential, CharSet = CharSet.Auto)]
    public struct MayDay_CONTEXT
    {
        public System.UInt32  dwIndex;   //previously was int
        public System.UInt32 dwVersion;  //previously was int  
        public System.UInt64 hLock;   //previously was int
        [MarshalAs(UnmanagedType.ByValArray, SizeConst = 12)]
        public byte[] reserve;
        [MarshalAs(UnmanagedType.ByValArray, SizeConst = 56)]
        public byte[] bAtr;
        [MarshalAs(UnmanagedType.ByValArray, SizeConst = 8)]
        public byte[] bID;
        public uint dwAtrLen;
    }

but in 32 bit OS, the following structure works:

    [StructLayout(LayoutKind.Sequential, CharSet = CharSet.Auto)]
    public struct MayDay_CONTEXT
    {
        public int  dwIndex;     //previously was int
        public int dwVersion;    //previously was int  
        public int hLock;     //previously was int
        [MarshalAs(UnmanagedType.ByValArray, SizeConst = 12)]
        public byte[] reserve;
        [MarshalAs(UnmanagedType.ByValArray, SizeConst = 56)]
        public byte[] bAtr;
        [MarshalAs(UnmanagedType.ByValArray, SizeConst = 8)]
        public byte[] bID;
        public uint dwAtrLen;
    }

Is there anyway to set the structure member's type at runtime? I know I need a kind of duck typing to do it, but maybe there is a better solution... any ideas?

+2  A: 

Would IntPtr (for hLock) work? Otherwise, you'll probably have to use #if definitions in your source... - i.e.

#if X86
     ..
#else
     ..
#endif

and define the X86 symbol in your 32-bit builds (there isn't anything built in)

Marc Gravell
As mentioned, I don't want to compile 2 versions of my C# code, so the #If #endif is not preferred.
Ngu Soon Hui
I think you missed the initial suggestion of using an IntPtr (which doesn't require a #if)
marklam
Ah, Your first solution ( changing UInt64 to IntPtr) works
Ngu Soon Hui