Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to pass an Optional parameter that is a struct in C# [duplicate]

So I've run into this unfortunate situation where I have to, as the title says, write a function declaration with an optional struct parameter.

Here is the struct:

[StructLayout(LayoutKind.Sequential)]
public struct SECURITY_ATTRIBUTES
{
  public int nLength;
  public IntPtr lpSecurityDescriptor;
  public int bInheritHandle;
}

Here is the function in the .dll advapi.dll:

LONG WINAPI RegSaveKey(
_In_     HKEY                  hKey,
_In_     LPCTSTR               lpFile,
_In_opt_ LPSECURITY_ATTRIBUTES lpSecurityAttributes
);

Here's my declaration so far:

[DllImport("advapi32.dll", SetLastError = true)]
static extern int RegSaveKey(UInt32 hKey, string lpFile, [optional parameter here!!] );
like image 386
Alvaromon Avatar asked Feb 02 '26 02:02

Alvaromon


1 Answers

For this, you should declare the 3rd argument as a IntPtr. When you want to pass it null, give it IntPtr.Zero. If you want to pass a real structure to it, Marshal the structure into memory - i.e. something like this

SECURITY_ATTRIBUTES sa = new SECURITY_ATTRIBUTES();
// set anything you want in the sa structure here

IntPtr pnt = Marshal.AllocHGlobal(Marshal.SizeOf(typeof(SECURITY_ATTRIBUTES)));
try {
    Marshal.StructureToPtr(sa, pnt, false)

    // call RegSaveKey here 
} finally {
    Marshal.FreeHGlobal(pnt);
}
like image 113
MrMikeJJ Avatar answered Feb 03 '26 15:02

MrMikeJJ



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!