I need to be using the following function from a native dll (WNSMP32.dll) in my C# code.
SNMPAPI_STATUS SnmpStartupEx( _Out_ smiLPUINT32 nMajorVersion,...);
//Considering just one for purpose of discussion
For this, I have the dllimport declaration as
[DllImport("wsnmp32.dll")] internal static extern
Status SnmpStartupEx(out IntPtr majorVersion, ...);
//Considering just one for purpose of discussion
I am using the function as
IntPtr majorVersion = Marshal.AllocHGlobal(sizeof(UINT32))
status = SnmpStartupEx(out majorVersion, out minVersion,
out level, out translateMode, out retransmitMode )
After the allocation of memory, I am printing the values of the IntPtr.
<<<DEBUG OUTPUT>>> IntPtr Value = 112235522816
However after the call to the , I find that the IntPtr is changing!
<<<DEBUG OUTPUT>>> IntPtr after calling SnmpStartupEx
<<<DEBUG OUTPUT>>> IntPtr Value = 111669149698
- Should I be allocating memory through Marshal.AllocHGlobal before the call?
- Is it valid for the IntPtr’s address to change after the call?
Try:
Every
outparameter is actually a pointer to a variable which the function overwrites. You don’t want to writeout IntPtrunless the native code has a double-pointer.You could do all of that yourself with
AllocHGlobaland a normal (pass-by-value, notout)IntPtrparameter… but why go to all that trouble when the compiler can do it for you (and the compiler will be faster, since it will take the address of local variables on the stack instead of allocating buffer space dynamically and then copying)?