Home > Blockchain >  How to use windows api GetPackagesByPackageFamily in CSharp?
How to use windows api GetPackagesByPackageFamily in CSharp?

Time:05-17

API [GetPackagesByPackageFamily] in appmodel.h

#include <Windows.h>
#include <appmodel.h>
...
WINBASEAPI
_Check_return_
_Success_(return == ERROR_SUCCESS)
_On_failure_(_Unchanged_(*count))
_On_failure_(_Unchanged_(*bufferLength))
LONG
WINAPI
GetPackagesByPackageFamily(
    _In_ PCWSTR packageFamilyName,
    _Inout_ UINT32* count,
    _Out_writes_opt_(*count) PWSTR* packageFullNames,
    _Inout_ UINT32* bufferLength,
    _Out_writes_opt_(*bufferLength) WCHAR* buffer
    );
...

I want to use it in C#, so I define it like this in C#.

[DllImport(@"kernel32.dll", CharSet = CharSet.Unicode, CallingConvention = CallingConvention.Winapi, EntryPoint = "GetPackagesByPackageFamily")]
private static extern long GetPackagesByPackageFamily(
    string packageFamilyName,
    ref uint count,
    out string[] packageFullNames,
    ref uint bufferLength,
    out string buffer);

But the call runs wrong, how can I modify it?

CodePudding user response:

You can have a look at this library: https://github.com/dahall/Vanara/ that offers exactly that P/Invoke.

They are implementing it like that:

[DllImport(Lib.Kernel32, SetLastError = false, ExactSpelling = true, CharSet = CharSet.Unicode)]
public static extern long GetPackagesByPackageFamily(string packageFamilyName, ref uint count, [Out, MarshalAs(UnmanagedType.LPArray, ArraySubType = UnmanagedType.LPWStr, SizeParamIndex = 1)] string[] packageFullNames, ref uint bufferLength, IntPtr buffer);

(see here https://github.com/dahall/Vanara/blob/3f64f6d9d4c963070e31823ca8a720068ac07fe2/PInvoke/Kernel32/AppModel.cs )

CodePudding user response:

thanks comment, Then call it like this.

  packageFullNames = new string[packageCount];
  buffer = Marshal.AllocCoTaskMem((int)bufferLength);
  var res = GetPackagesByPackageFamily( packageFamilyName, ref packageCount, packageFullNames, ref bufferLength, buffer);
  •  Tags:  
  • c# c
  • Related