Do you know how to make .NET wrapper work on both x64 and x86 platforms?

Last updated by Igor Goldobin about 2 months ago.See history

Sometimes, we need to use .NET wrapper to call Windows built-in forms for implementing special functionalities. For example, calling the Directory Object Picker dialog enables a user to select objects from the Active Directory. MSDN provides an article and an example(C++) on how to calling the Directory Object Picker dialog, and the CodePlex website gives a .Net version of implementation(C#).

However, all of this implementations only work on x86 platform, and will crash on x64 platform, regarding to this problem, the keynote is to understand the difference of IntPtr in between x64 and x86 platforms.

  • In x86 platform, IntPtr = Int32
  • In x64 platform, IntPtr = Int64

So, To fix the crash, we should re-write the code below:

DSOP_SCOPE_INIT_INFO[] scopeInitInfo = new DSOP_SCOPE_INIT_INFO[2]; 

IntPtr refScopeInitInfo = Marshal.AllocHGlobal(Marshal.SizeOf (typeof (DSOP_SCOPE_INIT_INFO)) * 2);
   
Marshal.StructureToPtr (scopeInitInfo[0], refScopeInitInfo,true);
 
Marshal.StructureToPtr(scopeInitInfo[1], (IntPtr)((int)refScopeInitInfo + Marshal.SizeOf(typeof(DSOP_SCOPE_INIT_INFO))), true);

Bad example - The code above always gets crash in x64 platform, because of an integer overflow and result in a segmentation fault in 64 bits.

IntPtr refScopeInitInfo = Marshal.AllocHGlobal(Marshal.SizeOf(typeof(DSOP_SCOPE_INIT_INFO)) * 2);

int scopeInitInfoSize = Marshal.SizeOf (typeof (DSOP_SCOPE_INIT_INFO));
 
int offset = scopeInitInfoSize;
 
IntPtr scopeInitInfo = (IntPtr)(refScopeInitInfo.ToInt64() + offset);

Good example - The Directory Object Picker dialog works on both x64 and x86 platforms well when using the good code above.

crash
Figure: Bad example - Calling the Directory Object Picker dialog causes crash on x64 platform when using the bad code above

worknormal
Figure: Good example - The Directory Object Picker dialog works on both x64 and x86 platforms well when using the good code above

We open source. Powered by GitHub