Win32 API 日本語リファレンス
ホームSecurity.Isolation › GetAppContainerNamedObjectPath

GetAppContainerNamedObjectPath

関数
AppContainerの名前付きオブジェクト用パスを取得する。
DLLKERNEL32.dll呼出規約winapiSetLastErrorあり対応OSwindows8.0

シグネチャ

// KERNEL32.dll
#include <windows.h>

BOOL GetAppContainerNamedObjectPath(
    HANDLE Token,   // optional
    PSID AppContainerSid,   // optional
    DWORD ObjectPathLength,
    LPWSTR ObjectPath,   // optional
    DWORD* ReturnLength
);

パラメーター

名前方向説明
TokenHANDLEinoptionalトークンに関するハンドル。NULL を渡し、かつ AppContainerSid パラメーターも渡さない場合は、呼び出し元の現在のプロセストークンが使用されます。偽装中の場合はスレッドトークンが使用されます。
AppContainerSidPSIDinoptionalアプリコンテナーの SID。
ObjectPathLengthDWORDinバッファーの長さ。
ObjectPathLPWSTRoutoptional名前付きオブジェクトパスが格納されるバッファー。
ReturnLengthDWORD*out名前付きオブジェクトパスを格納するために必要な長さを返します。

戻り値の型: BOOL

公式ドキュメント

アプリコンテナーの名前付きオブジェクトパスを取得します。

戻り値

関数が成功した場合、TRUE を返します。

関数が失敗した場合は、FALSE を返します。拡張エラー情報を取得するには、GetLastError を呼び出します。

解説(Remarks)

Windows ストアアプリとデスクトップアプリケーションの両方で動作し、Windows ストアアプリのコンテキストで読み込まれる機能を備えた支援技術ツールでは、コンテキスト内で動作する機能とツール本体との同期が必要になる場合があります。通常、このような同期はユーザーのセッションに名前付きオブジェクトを作成することで実現します。しかし、既定ではユーザーセッションやグローバルセッションの名前付きオブジェクトに Windows ストアアプリからアクセスできないため、この仕組みは Windows ストアアプリでは課題となります。このような問題を避けるため、支援技術ツールは UI オートメーション API または Magnification API を使用するように更新することをお勧めします。それまでの間は、名前付きオブジェクトを引き続き使用する必要がある場合があります。

次のサンプルは、Windows ストアアプリからアクセスできるように名前付きオブジェクトを作成します。

#pragma comment(lib, "advapi32.lib")
#include <windows.h>
#include <stdio.h>
#include <aclapi.h>
#include <tchar.h>

int main(void)
{
BOOL GetLogonSid (HANDLE hToken, PSID *ppsid) 
{
    BOOL bSuccess = FALSE;
    DWORD dwLength = 0;
    PTOKEN_GROUPS ptg = NULL;

    // Verify the parameter passed in is not NULL.
    if (NULL == ppsid)
        goto Cleanup;

    // Get required buffer size and allocate the TOKEN_GROUPS buffer.

    if (!GetTokenInformation(
            hToken,         // handle to the access token
            TokenLogonSid,    // get information about the token's groups 
            (LPVOID) ptg,   // pointer to TOKEN_GROUPS buffer
            0,              // size of buffer
            &dwLength       // receives required buffer size
        )) 
    {
        if (GetLastError() != ERROR_INSUFFICIENT_BUFFER) 
            goto Cleanup;

        ptg = (PTOKEN_GROUPS)HeapAlloc(GetProcessHeap(),
                                    HEAP_ZERO_MEMORY, dwLength);

        if (ptg == NULL)
            goto Cleanup;
    }

    // Get the token group information from the access token.

    if (!GetTokenInformation(
            hToken,         // handle to the access token
            TokenLogonSid,    // get information about the token's groups 
            (LPVOID) ptg,   // pointer to TOKEN_GROUPS buffer
            dwLength,       // size of buffer
            &dwLength       // receives required buffer size
            ) || ptg->GroupCount != 1) 
    {
        goto Cleanup;
    }

    // Found the logon SID; make a copy of it.

    dwLength = GetLengthSid(ptg->Groups[0].Sid);
    *ppsid = (PSID) HeapAlloc(GetProcessHeap(),
                HEAP_ZERO_MEMORY, dwLength);
    if (*ppsid == NULL)
        goto Cleanup;
    if (!CopySid(dwLength, *ppsid, ptg->Groups[0].Sid)) 
    {
        HeapFree(GetProcessHeap(), 0, (LPVOID)*ppsid);
        goto Cleanup;
    }

   bSuccess = TRUE;

Cleanup: 

    // Free the buffer for the token groups.

    if (ptg != NULL)
        HeapFree(GetProcessHeap(), 0, (LPVOID)ptg);

    return bSuccess;
}

BOOL
CreateObjectSecurityDescriptor(PSID pLogonSid, PSECURITY_DESCRIPTOR* ppSD)
{
    BOOL bSuccess = FALSE;
    DWORD dwRes;
    PSID pAllAppsSID = NULL;
    PACL pACL = NULL;
    PSECURITY_DESCRIPTOR pSD = NULL;
    EXPLICIT_ACCESS ea[2];
    SID_IDENTIFIER_AUTHORITY ApplicationAuthority = SECURITY_APP_PACKAGE_AUTHORITY;

    // Create a well-known SID for the all appcontainers group.
    if(!AllocateAndInitializeSid(&ApplicationAuthority, 
            SECURITY_BUILTIN_APP_PACKAGE_RID_COUNT,
            SECURITY_APP_PACKAGE_BASE_RID,
            SECURITY_BUILTIN_PACKAGE_ANY_PACKAGE,
            0, 0, 0, 0, 0, 0,
            &pAllAppsSID))
    {
        wprintf(L"AllocateAndInitializeSid Error %u\n", GetLastError());
        goto Cleanup;
    }

    // Initialize an EXPLICIT_ACCESS structure for an ACE.
    // The ACE will allow LogonSid generic all access
    ZeroMemory(&ea, 2 * sizeof(EXPLICIT_ACCESS));
    ea[0].grfAccessPermissions = STANDARD_RIGHTS_ALL | MUTEX_ALL_ACCESS;
    ea[0].grfAccessMode = SET_ACCESS;
    ea[0].grfInheritance= NO_INHERITANCE;
    ea[0].Trustee.TrusteeForm = TRUSTEE_IS_SID;
    ea[0].Trustee.TrusteeType = TRUSTEE_IS_USER;
    ea[0].Trustee.ptstrName  = (LPTSTR) pLogonSid;

    // Initialize an EXPLICIT_ACCESS structure for an ACE.
    // The ACE will allow the all appcontainers execute permission
    ea[1].grfAccessPermissions = STANDARD_RIGHTS_READ | STANDARD_RIGHTS_EXECUTE | SYNCHRONIZE | MUTEX_MODIFY_STATE;
    ea[1].grfAccessMode = SET_ACCESS;
    ea[1].grfInheritance= NO_INHERITANCE;
    ea[1].Trustee.TrusteeForm = TRUSTEE_IS_SID;
    ea[1].Trustee.TrusteeType = TRUSTEE_IS_GROUP;
    ea[1].Trustee.ptstrName  = (LPTSTR) pAllAppsSID;

    // Create a new ACL that contains the new ACEs.
    dwRes = SetEntriesInAcl(2, ea, NULL, &pACL);
    if (ERROR_SUCCESS != dwRes) 
    {
        wprintf(L"SetEntriesInAcl Error %u\n", GetLastError());
        goto Cleanup;
    }

    // Initialize a security descriptor.  
    pSD = (PSECURITY_DESCRIPTOR) LocalAlloc(LPTR, 
                             SECURITY_DESCRIPTOR_MIN_LENGTH); 
    if (NULL == pSD) 
    { 
        wprintf(L"LocalAlloc Error %u\n", GetLastError());
        goto Cleanup; 
    } 
 
    if (!InitializeSecurityDescriptor(pSD,
            SECURITY_DESCRIPTOR_REVISION)) 
    {  
        wprintf(L"InitializeSecurityDescriptor Error %u\n",
                                GetLastError());
        goto Cleanup; 
    } 
 
    // Add the ACL to the security descriptor. 
    if (!SetSecurityDescriptorDacl(pSD, 
            TRUE,     // bDaclPresent flag   
            pACL, 
            FALSE))   // not a default DACL 
    {  
        wprintf(L"SetSecurityDescriptorDacl Error %u\n",
                GetLastError());
        goto Cleanup; 
    } 

    *ppSD = pSD;
    pSD = NULL;
    bSuccess = TRUE;
Cleanup:

    if (pAllAppsSID) 
        FreeSid(pAllAppsSID);
    if (pACL) 
        LocalFree(pACL);
    if (pSD) 
        LocalFree(pSD);

    return bSuccess;
}

    PSID pLogonSid = NULL;
    PSECURITY_DESCRIPTOR pSd = NULL;
    SECURITY_ATTRIBUTES  SecurityAttributes;
    HANDLE hToken = NULL;
    HANDLE hMutex = NULL;

    //Allowing LogonSid and all appcontainers. 
    if (GetLogonSid(hToken, &pLogonSid) && CreateObjectSecurityDescriptor(pLogonSid, &pSd) )
    {
        SecurityAttributes.nLength = sizeof(SECURITY_ATTRIBUTES);
        SecurityAttributes.bInheritHandle = TRUE;
        SecurityAttributes.lpSecurityDescriptor = pSd;

        hMutex = CreateMutex( 
                    &SecurityAttributes,         // default security descriptor
                    FALSE,                       // mutex not owned
                    TEXT("NameOfMutexObject"));  // object name
    }

    return 0;
}
出典・ライセンス: 上記「公式ドキュメント」の内容は Microsoft の Win32 API ドキュメント(MicrosoftDocs/sdk-api)を日本語に翻訳・改変したものです。© Microsoft Corporation. CC BY 4.0 で提供。
Microsoft 公式リファレンス: 英語 (en-us) · 日本語 (ja-jp) · 原文ソース (GitHub)

各言語での呼び出し定義

// KERNEL32.dll
#include <windows.h>

BOOL GetAppContainerNamedObjectPath(
    HANDLE Token,   // optional
    PSID AppContainerSid,   // optional
    DWORD ObjectPathLength,
    LPWSTR ObjectPath,   // optional
    DWORD* ReturnLength
);
[return: MarshalAs(UnmanagedType.Bool)]
[DllImport("KERNEL32.dll", SetLastError = true, ExactSpelling = true)]
static extern bool GetAppContainerNamedObjectPath(
    IntPtr Token,   // HANDLE optional
    IntPtr AppContainerSid,   // PSID optional
    uint ObjectPathLength,   // DWORD
    [MarshalAs(UnmanagedType.LPWStr)] System.Text.StringBuilder ObjectPath,   // LPWSTR optional, out
    out uint ReturnLength   // DWORD* out
);
<DllImport("KERNEL32.dll", SetLastError:=True, ExactSpelling:=True)>
Public Shared Function GetAppContainerNamedObjectPath(
    Token As IntPtr,   ' HANDLE optional
    AppContainerSid As IntPtr,   ' PSID optional
    ObjectPathLength As UInteger,   ' DWORD
    <MarshalAs(UnmanagedType.LPWStr)> ObjectPath As System.Text.StringBuilder,   ' LPWSTR optional, out
    <Out> ByRef ReturnLength As UInteger   ' DWORD* out
) As <MarshalAs(UnmanagedType.Bool)> Boolean
End Function
' Token : HANDLE optional
' AppContainerSid : PSID optional
' ObjectPathLength : DWORD
' ObjectPath : LPWSTR optional, out
' ReturnLength : DWORD* out
Declare PtrSafe Function GetAppContainerNamedObjectPath Lib "kernel32" ( _
    ByVal Token As LongPtr, _
    ByVal AppContainerSid As LongPtr, _
    ByVal ObjectPathLength As Long, _
    ByVal ObjectPath As LongPtr, _
    ByRef ReturnLength As Long) As Long
' VBA7前提(PtrSafe)。32bit Office では LongPtr→Long。Integer=16bit / Long=32bit / LongLong=64bit。
import ctypes
from ctypes import wintypes

GetAppContainerNamedObjectPath = ctypes.windll.kernel32.GetAppContainerNamedObjectPath
GetAppContainerNamedObjectPath.restype = wintypes.BOOL
GetAppContainerNamedObjectPath.argtypes = [
    wintypes.HANDLE,  # Token : HANDLE optional
    wintypes.HANDLE,  # AppContainerSid : PSID optional
    wintypes.DWORD,  # ObjectPathLength : DWORD
    wintypes.LPWSTR,  # ObjectPath : LPWSTR optional, out
    ctypes.POINTER(wintypes.DWORD),  # ReturnLength : DWORD* out
]
# GetLastError: use ctypes.GetLastError() (or ctypes.WinDLL(use_last_error=True))
require 'fiddle'
require 'fiddle/import'

lib = Fiddle.dlopen('KERNEL32.dll')
GetAppContainerNamedObjectPath = Fiddle::Function.new(
  lib['GetAppContainerNamedObjectPath'],
  [
    Fiddle::TYPE_VOIDP,  # Token : HANDLE optional
    Fiddle::TYPE_VOIDP,  # AppContainerSid : PSID optional
    -Fiddle::TYPE_INT,  # ObjectPathLength : DWORD
    Fiddle::TYPE_VOIDP,  # ObjectPath : LPWSTR optional, out
    Fiddle::TYPE_VOIDP,  # ReturnLength : DWORD* out
  ],
  Fiddle::TYPE_INT)
#[link(name = "kernel32")]
extern "system" {
    fn GetAppContainerNamedObjectPath(
        Token: *mut core::ffi::c_void,  // HANDLE optional
        AppContainerSid: *mut core::ffi::c_void,  // PSID optional
        ObjectPathLength: u32,  // DWORD
        ObjectPath: *mut u16,  // LPWSTR optional, out
        ReturnLength: *mut u32  // DWORD* out
    ) -> i32;
}
// crates: windows-sys provides ready-made bindings for this API.
$sig = @"
[return: MarshalAs(UnmanagedType.Bool)]
[DllImport("KERNEL32.dll", SetLastError = true)]
public static extern bool GetAppContainerNamedObjectPath(IntPtr Token, IntPtr AppContainerSid, uint ObjectPathLength, [MarshalAs(UnmanagedType.LPWStr)] System.Text.StringBuilder ObjectPath, out uint ReturnLength);
"@
$api = Add-Type -MemberDefinition $sig -Name 'KERNEL32_GetAppContainerNamedObjectPath' -Namespace Win32 -PassThru
# $api::GetAppContainerNamedObjectPath(Token, AppContainerSid, ObjectPathLength, ObjectPath, ReturnLength)
#uselib "KERNEL32.dll"
#func global GetAppContainerNamedObjectPath "GetAppContainerNamedObjectPath" sptr, sptr, sptr, sptr, sptr
; GetAppContainerNamedObjectPath Token, AppContainerSid, ObjectPathLength, varptr(ObjectPath), varptr(ReturnLength)   ; 戻り値は stat
; Token : HANDLE optional -> "sptr"
; AppContainerSid : PSID optional -> "sptr"
; ObjectPathLength : DWORD -> "sptr"
; ObjectPath : LPWSTR optional, out -> "sptr"
; ReturnLength : DWORD* out -> "sptr"
; ※HSP3.7は #func のため戻り値はシステム変数 stat に格納されます。
出力引数:
#uselib "KERNEL32.dll"
#cfunc global GetAppContainerNamedObjectPath "GetAppContainerNamedObjectPath" sptr, sptr, int, var, var
; res = GetAppContainerNamedObjectPath(Token, AppContainerSid, ObjectPathLength, ObjectPath, ReturnLength)
; Token : HANDLE optional -> "sptr"
; AppContainerSid : PSID optional -> "sptr"
; ObjectPathLength : DWORD -> "int"
; ObjectPath : LPWSTR optional, out -> "var"
; ReturnLength : DWORD* out -> "var"
; ※出力/バッファ引数は var 方式(変数を直接渡す)。varptr 方式にも切替可。
出力引数:
; BOOL GetAppContainerNamedObjectPath(HANDLE Token, PSID AppContainerSid, DWORD ObjectPathLength, LPWSTR ObjectPath, DWORD* ReturnLength)
#uselib "KERNEL32.dll"
#cfunc global GetAppContainerNamedObjectPath "GetAppContainerNamedObjectPath" intptr, intptr, int, var, var
; res = GetAppContainerNamedObjectPath(Token, AppContainerSid, ObjectPathLength, ObjectPath, ReturnLength)
; Token : HANDLE optional -> "intptr"
; AppContainerSid : PSID optional -> "intptr"
; ObjectPathLength : DWORD -> "int"
; ObjectPath : LPWSTR optional, out -> "var"
; ReturnLength : DWORD* out -> "var"
; ※出力/バッファ引数は var 方式(変数を直接渡す)。varptr 方式にも切替可。
import (
	"golang.org/x/sys/windows"
	"unsafe"
)

var (
	kernel32 = windows.NewLazySystemDLL("KERNEL32.dll")
	procGetAppContainerNamedObjectPath = kernel32.NewProc("GetAppContainerNamedObjectPath")
)

// Token (HANDLE optional), AppContainerSid (PSID optional), ObjectPathLength (DWORD), ObjectPath (LPWSTR optional, out), ReturnLength (DWORD* out)
r1, _, err := procGetAppContainerNamedObjectPath.Call(
	uintptr(Token),
	uintptr(AppContainerSid),
	uintptr(ObjectPathLength),
	uintptr(ObjectPath),
	uintptr(ReturnLength),
)
_ = err  // syscall.Errno (valid when the call sets last-error)
_ = r1   // BOOL
function GetAppContainerNamedObjectPath(
  Token: THandle;   // HANDLE optional
  AppContainerSid: THandle;   // PSID optional
  ObjectPathLength: DWORD;   // DWORD
  ObjectPath: PWideChar;   // LPWSTR optional, out
  ReturnLength: Pointer   // DWORD* out
): BOOL; stdcall;
  external 'KERNEL32.dll' name 'GetAppContainerNamedObjectPath';
result := DllCall("KERNEL32\GetAppContainerNamedObjectPath"
    , "Ptr", Token   ; HANDLE optional
    , "Ptr", AppContainerSid   ; PSID optional
    , "UInt", ObjectPathLength   ; DWORD
    , "Ptr", ObjectPath   ; LPWSTR optional, out
    , "Ptr", ReturnLength   ; DWORD* out
    , "Int")   ; return: BOOL
●GetAppContainerNamedObjectPath(Token, AppContainerSid, ObjectPathLength, ObjectPath, ReturnLength) = DLL("KERNEL32.dll", "bool GetAppContainerNamedObjectPath(void*, void*, dword, char*, void*)")
# 呼び出し: GetAppContainerNamedObjectPath(Token, AppContainerSid, ObjectPathLength, ObjectPath, ReturnLength)
# Token : HANDLE optional -> "void*"
# AppContainerSid : PSID optional -> "void*"
# ObjectPathLength : DWORD -> "dword"
# ObjectPath : LPWSTR optional, out -> "char*"
# ReturnLength : DWORD* out -> "void*"
# なでしこ1は32bit・ANSI(Shift_JIS)。文字列=char*(ANSI)、ポインタ/ハンドル=void*(4byte)。
const std = @import("std");

extern "kernel32" fn GetAppContainerNamedObjectPath(
    Token: ?*anyopaque, // HANDLE optional
    AppContainerSid: ?*anyopaque, // PSID optional
    ObjectPathLength: u32, // DWORD
    ObjectPath: [*c]u16, // LPWSTR optional, out
    ReturnLength: [*c]u32 // DWORD* out
) callconv(std.os.windows.WINAPI) i32;
proc GetAppContainerNamedObjectPath(
    Token: pointer,  # HANDLE optional
    AppContainerSid: pointer,  # PSID optional
    ObjectPathLength: uint32,  # DWORD
    ObjectPath: ptr uint16,  # LPWSTR optional, out
    ReturnLength: ptr uint32  # DWORD* out
): int32 {.importc: "GetAppContainerNamedObjectPath", stdcall, dynlib: "KERNEL32.dll".}
pragma(lib, "kernel32");
extern(Windows)
int GetAppContainerNamedObjectPath(
    void* Token,   // HANDLE optional
    void* AppContainerSid,   // PSID optional
    uint ObjectPathLength,   // DWORD
    wchar* ObjectPath,   // LPWSTR optional, out
    uint* ReturnLength   // DWORD* out
);
ccall((:GetAppContainerNamedObjectPath, "KERNEL32.dll"), stdcall, Int32,
      (Ptr{Cvoid}, Ptr{Cvoid}, UInt32, Ptr{UInt16}, Ptr{UInt32}),
      Token, AppContainerSid, ObjectPathLength, ObjectPath, ReturnLength)
# Token : HANDLE optional -> Ptr{Cvoid}
# AppContainerSid : PSID optional -> Ptr{Cvoid}
# ObjectPathLength : DWORD -> UInt32
# ObjectPath : LPWSTR optional, out -> Ptr{UInt16}
# ReturnLength : DWORD* out -> Ptr{UInt32}
# stdcall は 32bit のみ意味を持つ(x64 では無視)。
local ffi = require("ffi")
ffi.cdef[[
int32_t GetAppContainerNamedObjectPath(
    void* Token,
    void* AppContainerSid,
    uint32_t ObjectPathLength,
    uint16_t* ObjectPath,
    uint32_t* ReturnLength);
]]
local kernel32 = ffi.load("kernel32")
-- kernel32.GetAppContainerNamedObjectPath(Token, AppContainerSid, ObjectPathLength, ObjectPath, ReturnLength)
-- Token : HANDLE optional
-- AppContainerSid : PSID optional
-- ObjectPathLength : DWORD
-- ObjectPath : LPWSTR optional, out
-- ReturnLength : DWORD* out
-- 構造体/GUIDへのポインタは cdef が通るよう void* で表記(実型は各引数コメント参照)。値渡し構造体・enum は対応する typedef を cdef に追加すること。
const koffi = require('koffi');
const lib = koffi.load('KERNEL32.dll');
const GetAppContainerNamedObjectPath = lib.func('__stdcall', 'GetAppContainerNamedObjectPath', 'int32_t', ['void *', 'void *', 'uint32_t', 'uint16_t *', 'uint32_t *']);
// GetAppContainerNamedObjectPath(Token, AppContainerSid, ObjectPathLength, ObjectPath, ReturnLength)
// Token : HANDLE optional -> 'void *'
// AppContainerSid : PSID optional -> 'void *'
// ObjectPathLength : DWORD -> 'uint32_t'
// ObjectPath : LPWSTR optional, out -> 'uint16_t *'
// ReturnLength : DWORD* out -> 'uint32_t *'
// 出力ポインタは koffi.out(...) で包む。構造体は koffi.struct で定義。
const lib = Deno.dlopen("KERNEL32.dll", {
  GetAppContainerNamedObjectPath: { parameters: ["pointer", "pointer", "u32", "buffer", "pointer"], result: "i32" },
});
// lib.symbols.GetAppContainerNamedObjectPath(Token, AppContainerSid, ObjectPathLength, ObjectPath, ReturnLength)
// Token : HANDLE optional -> "pointer"
// AppContainerSid : PSID optional -> "pointer"
// ObjectPathLength : DWORD -> "u32"
// ObjectPath : LPWSTR optional, out -> "buffer"
// ReturnLength : DWORD* out -> "pointer"
// 文字列引数は "buffer"(NUL 終端のバイト列を Uint8Array で渡す)。
// 値渡し構造体は { struct: [ ...field types... ] } を使用。
<?php
$ffi = FFI::cdef(<<<C
int32_t GetAppContainerNamedObjectPath(
    void* Token,
    void* AppContainerSid,
    uint32_t ObjectPathLength,
    uint16_t* ObjectPath,
    uint32_t* ReturnLength);
C, "KERNEL32.dll");
// $ffi->GetAppContainerNamedObjectPath(Token, AppContainerSid, ObjectPathLength, ObjectPath, ReturnLength);
// Token : HANDLE optional
// AppContainerSid : PSID optional
// ObjectPathLength : DWORD
// ObjectPath : LPWSTR optional, out
// ReturnLength : DWORD* out
// 構造体/GUIDへのポインタは cdef が通るよう void* で表記(実型は各引数コメント参照)。値渡し構造体・enum は対応する typedef を cdef に追加すること。
// WINAPI(stdcall): x64 では呼出規約が統一されるため問題なし。x86 では __stdcall 対応のラッパが必要な場合あり。
import com.sun.jna.*;
import com.sun.jna.ptr.*;
import com.sun.jna.win32.StdCallLibrary;
import com.sun.jna.win32.W32APIOptions;

public interface Kernel32 extends StdCallLibrary {
    Kernel32 INSTANCE = Native.load("kernel32", Kernel32.class);
    boolean GetAppContainerNamedObjectPath(
        Pointer Token,   // HANDLE optional
        Pointer AppContainerSid,   // PSID optional
        int ObjectPathLength,   // DWORD
        char[] ObjectPath,   // LPWSTR optional, out
        IntByReference ReturnLength   // DWORD* out
    );
}
@[Link("kernel32")]
lib LibKERNEL32
  fun GetAppContainerNamedObjectPath = GetAppContainerNamedObjectPath(
    Token : Void*,   # HANDLE optional
    AppContainerSid : Void*,   # PSID optional
    ObjectPathLength : UInt32,   # DWORD
    ObjectPath : UInt16*,   # LPWSTR optional, out
    ReturnLength : UInt32*   # DWORD* out
  ) : Int32
end
# 構造体/GUID/enum は lib 内に対応する型定義が必要。
# 呼出規約: x64 は規約統一のため OK。x86(32bit)は WINAPI=stdcall だが Crystal の fun に stdcall 付与構文がなく非対応。
import 'dart:ffi';
import 'package:ffi/ffi.dart';

typedef GetAppContainerNamedObjectPathNative = Int32 Function(Pointer<Void>, Pointer<Void>, Uint32, Pointer<Utf16>, Pointer<Uint32>);
typedef GetAppContainerNamedObjectPathDart = int Function(Pointer<Void>, Pointer<Void>, int, Pointer<Utf16>, Pointer<Uint32>);
final GetAppContainerNamedObjectPath = DynamicLibrary.open('KERNEL32.dll')
    .lookupFunction<GetAppContainerNamedObjectPathNative, GetAppContainerNamedObjectPathDart>('GetAppContainerNamedObjectPath');
// Token : HANDLE optional -> Pointer<Void>
// AppContainerSid : PSID optional -> Pointer<Void>
// ObjectPathLength : DWORD -> Uint32
// ObjectPath : LPWSTR optional, out -> Pointer<Utf16>
// ReturnLength : DWORD* out -> Pointer<Uint32>
// 文字列は package:ffi の "...".toNativeUtf16()/toNativeUtf8() で変換。
{$mode objfpc}{$H+}
function GetAppContainerNamedObjectPath(
  Token: THandle;   // HANDLE optional
  AppContainerSid: THandle;   // PSID optional
  ObjectPathLength: DWORD;   // DWORD
  ObjectPath: PWideChar;   // LPWSTR optional, out
  ReturnLength: Pointer   // DWORD* out
): BOOL; stdcall;
  external 'KERNEL32.dll' name 'GetAppContainerNamedObjectPath';
import Foreign
import Foreign.C.Types
import Foreign.C.String

foreign import stdcall safe "GetAppContainerNamedObjectPath"
  c_GetAppContainerNamedObjectPath :: Ptr () -> Ptr () -> Word32 -> CWString -> Ptr Word32 -> IO CInt
-- Token : HANDLE optional -> Ptr ()
-- AppContainerSid : PSID optional -> Ptr ()
-- ObjectPathLength : DWORD -> Word32
-- ObjectPath : LPWSTR optional, out -> CWString
-- ReturnLength : DWORD* out -> Ptr Word32
-- 要 GHC(Windows)。stdcall は x64 では ccall として扱われる。ブロックする API は safe 呼び出し推奨。
open Ctypes
open Foreign

let getappcontainernamedobjectpath =
  foreign "GetAppContainerNamedObjectPath"
    ((ptr void) @-> (ptr void) @-> uint32_t @-> (ptr uint16_t) @-> (ptr uint32_t) @-> returning int32_t)
(* Token : HANDLE optional -> (ptr void) *)
(* AppContainerSid : PSID optional -> (ptr void) *)
(* ObjectPathLength : DWORD -> uint32_t *)
(* ObjectPath : LPWSTR optional, out -> (ptr uint16_t) *)
(* ReturnLength : DWORD* out -> (ptr uint32_t) *)
(* foreign は cdecl 前提。x64 Windows では WINAPI と一致。構造体は ctypes structure を定義のこと。 *)
(cffi:define-foreign-library kernel32 (t "KERNEL32.dll"))
(cffi:use-foreign-library kernel32)

(cffi:defcfun ("GetAppContainerNamedObjectPath" get-app-container-named-object-path :convention :stdcall) :int32
  (token :pointer)   ; HANDLE optional
  (app-container-sid :pointer)   ; PSID optional
  (object-path-length :uint32)   ; DWORD
  (object-path :pointer)   ; LPWSTR optional, out
  (return-length :pointer))   ; DWORD* out
; isize/usize(INT_PTR/SIZE_T)は x64 前提で :int64/:uint64。x86 では :int32/:uint32。
use Win32::API;
my $GetAppContainerNamedObjectPath = Win32::API::More->new('KERNEL32',
    'BOOL GetAppContainerNamedObjectPath(HANDLE Token, HANDLE AppContainerSid, DWORD ObjectPathLength, LPWSTR ObjectPath, LPVOID ReturnLength)');
# my $ret = $GetAppContainerNamedObjectPath->Call($Token, $AppContainerSid, $ObjectPathLength, $ObjectPath, $ReturnLength);
# Token : HANDLE optional -> HANDLE
# AppContainerSid : PSID optional -> HANDLE
# ObjectPathLength : DWORD -> DWORD
# ObjectPath : LPWSTR optional, out -> LPWSTR
# ReturnLength : DWORD* out -> LPVOID
# 値渡し構造体は pack() した文字列、または Win32::API::Struct を使用。