Thursday, June 12, 2008

PInvoke DhcpGetServerBindingInfo / DhcpSetServerBindingInfo C# ulong gotcha

Phew!! there is a thing always to remember while pinvoking. ulong is 64bit in c# while 32 bit in win32 world. Learned it hard way .. :)..
The error that you will get if you try to pinvoke if "null reference" .
Here is the signature and code snippet to be used.

[DllImport("dhcpsapi.dll", SetLastError = true, CharSet = CharSet.Unicode)]
public static extern uint DhcpGetServerBindingInfo(
[MarshalAs(UnmanagedType.LPWStr)]
string ServerIpAddress,
uint Flags,
out IntPtr BindElementsInfo);

[DllImport("dhcpsapi.dll", SetLastError = true, CharSet = CharSet.Unicode)]
public static extern uint DhcpSetServerBindingInfo(
[MarshalAs(UnmanagedType.LPWStr)]
string ServerIpAddress,
uint Flags,
IntPtr BindElementsInfo);


How to call:
IntPtr intptrBindElemArray = new IntPtr();
UInt32 ret;
ret = DhcpGetServerBindingInfo(localIP,
0,
out intptrBindElemArray);
if (ret != 0)
{
int code = 0;
code = (int)ret;
Win32Exception winex = new Win32Exception(code);
handleDHCPError(winex.NativeErrorCode + " : " + winex.Message);
}

Simple right.
Just that searched the hell lot but nobody in the world did it before ... :).

2 comments:

Unknown said...

Hi Amit,
Appreciate the post, it rescued me from hours of frustration... I'm now wondering how you marshaled the data structures returned by the call. Did you write a custom marshaller or did you use a different method? Any pointers would be appreciated. -Dan

Amit Lal a.k.a reddd said...

Great to learn this helped. Opening this blog after a looong time myself. Sorry didnt answer your question on time. But surely this doesnt need any custom marshalling. Will try to find my old code and see if i can put some more info.