sonofdelphi
sonofdelphi

Reputation: 2036

Using out parameters of a native DLL from C#

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
  1. Should I be allocating memory through Marshal.AllocHGlobal before the call?
  2. Is it valid for the IntPtr's address to change after the call?

Upvotes: 4

Views: 9020

Answers (1)

Ben Voigt
Ben Voigt

Reputation: 283634

Try:

[DllImport("wsnmp32.dll")]
internal static extern Status SnmpStartupEx(out UInt32 majorVersion,
                                            out UInt32 minorVersion, 
                                            out UInt32 level,
                                            out UInt32 translateMode,
                                            out UInt32 retransmitMode);

Every out parameter is actually a pointer to a variable which the function overwrites. You don't want to write out IntPtr unless the native code has a double-pointer.

You could do all of that yourself with AllocHGlobal and a normal (pass-by-value, not out) IntPtr parameter... 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)?

Upvotes: 7

Related Questions