Win32 API 日本語リファレンス
ホームUI.Shell › PathCanonicalizeW

PathCanonicalizeW

関数
相対指定を解決しパスを正規形に整える。
DLLSHLWAPI.dll文字セットUnicode (-W)呼出規約winapiSetLastErrorあり対応OSWindows 2000 以降

シグネチャ

// SHLWAPI.dll  (Unicode / -W)
#include <windows.h>

BOOL PathCanonicalizeW(
    LPWSTR pszBuf,
    LPCWSTR pszPath
);

パラメーター

名前方向説明
pszBufLPWSTRout正規化されたパスを受け取る文字列へのポインターです。返される文字列を確実に格納できるよう、このバッファーのサイズは MAX_PATH に設定する必要があります。
pszPathLPCWSTRin正規化するパスを格納した、最大長 MAX_PATH の null 終端文字列へのポインターです。

戻り値の型: BOOL

公式ドキュメント

"." や ".." などのナビゲーション要素を取り除いてパスを単純化し、直接的で整形式のパスを生成します。(Unicode)

戻り値

型: BOOL

結果が計算され、lpszDst 出力バッファーの内容が有効である場合は TRUE を返します。それ以外の場合は FALSE を返し、lpszDst が指すバッファーの内容は無効です。拡張エラー情報を取得するには、GetLastError を呼び出してください。

解説(Remarks)

この関数では、特殊な文字シーケンスをパスに挿入することで、パスから何を取り除くかをユーザーが指定できます。".." シーケンスは、現在位置から 1 つ前のパスセグメントまでのパスセグメントを取り除くことを示します。"." シーケンスは、次のパスセグメントを読み飛ばして、その後のパスセグメントへ進むことを示します。パスのルートセグメントは取り除けません。

パスセグメントの数よりも ".." シーケンスの数の方が多い場合、この関数は TRUE を返し、lpszDst が指すバッファーの内容はルートのみ、すなわち "" になります。


#include <windows.h>
#include <iostream>
#include "Shlwapi.h"

using namespace std;

int main( void )
{
// Path_1 destination buffer.
char buffer_1[MAX_PATH] = "JustABufferToHoldTheCanonicalizedPathForAnExample";
char *lpStr1;
lpStr1 = buffer_1;

// Path_2 to be Canonicalized.
char buffer_2[ ] = "A:\\name_1\\.\\name_2\\..\\name_3";
char *lpStr2;
lpStr2 = buffer_2;

// Path_3 to be Canonicalized.
char buffer_3[ ] = "A:\\name_1\\..\\name_2\\.\\name_3";
char *lpStr3;
lpStr3 = buffer_3;

// Path_4 to be Canonicalized.
char buffer_4[ ] = "A:\\name_1\\name_2\\.\\name_3\\..\\name_4";
char *lpStr4;
lpStr4 = buffer_4;

// Path_5 to be Canonicalized.
char buffer_5[ ] = "A:\\name_1\\.\\name_2\\.\\name_3\\..\\name_4\\..";
char *lpStr5;
lpStr5 = buffer_5;

// Path_6 to be Canonicalized.
char buffer_6[ ] = "C:\\..";
char *lpStr6;
lpStr6 = buffer_6;

cout << "The un-canonicalized path 2 is : " << lpStr2
     << "\nThe return value is            : " 
     << PathCanonicalize(lpStr1,lpStr2)
     << "\nThe canonicalized path 1 is    : " << lpStr1 << endl;

cout << "\nThe un-canonicalized path 3 is : " << lpStr3
     << "\nThe return value is            : " 
     << PathCanonicalize(lpStr1,lpStr3)
     << "\nThe canonicalized path 1 is    : " << lpStr1 << endl;

cout << "\nThe un-canonicalized path 4 is : " << lpStr4
     << "\nThe return value is            : " 
     << PathCanonicalize(lpStr1,lpStr4)
     << "\nThe canonicalized path 1 is    : " << lpStr1 << endl;

cout << "\nThe un-canonicalized path 5 is : " << lpStr5
     << "\nThe return value is            : " 
     << PathCanonicalize(lpStr1,lpStr5) 
     << "\nThe canonicalized path 1 is    : " << lpStr1 << endl;

cout << "\nThe un-canonicalized path 6 is : " << lpStr6
     << "\nThe return value is            : " 
     << PathCanonicalize(lpStr1,lpStr6)
     << "\nThe canonicalized path 1 is    : " << lpStr1 << endl;
}
OUTPUT:
---------
The un-canonicalized path 2 is : A:\name_1\.\name_2\..\name_3
The return value is            : 1
The canonicalized path 1 is    : A:\name_1\name_3

The un-canonicalized path 3 is : A:\name_1\..\name_2\.\name_3
The return value is            : 1
The canonicalized path 1 is    : A:\name_2\name_3

The un-canonicalized path 4 is : A:\name_1\name_2\.\name_3\..\name_4
The return value is            : 1
The canonicalized path 1 is    : A:\name_1\name_2\name_4

The un-canonicalized path 5 is : A:\name_1\.\name_2\.\name_3\..\name_4\..
The return value is            : 1
The canonicalized path 1 is    : A:\name_1\name_2

The un-canonicalized path 6 is : C:\..
The return value is            : 1
The canonicalized path 1 is    : C:\
メモ

shlwapi.h ヘッダーは PathCanonicalize を、UNICODE プリプロセッサ定数の定義に基づいてこの関数の ANSI 版または Unicode 版を自動的に選択するエイリアスとして定義しています。エンコーディング中立なエイリアスの使用を、エンコーディング中立でないコードと混在させると、不一致が生じてコンパイルエラーや実行時エラーを引き起こす可能性があります。詳しくは「Conventions for Function Prototypes」を参照してください。

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

各言語での呼び出し定義

// SHLWAPI.dll  (Unicode / -W)
#include <windows.h>

BOOL PathCanonicalizeW(
    LPWSTR pszBuf,
    LPCWSTR pszPath
);
[return: MarshalAs(UnmanagedType.Bool)]
[DllImport("SHLWAPI.dll", CharSet = CharSet.Unicode, SetLastError = true, ExactSpelling = true)]
static extern bool PathCanonicalizeW(
    [MarshalAs(UnmanagedType.LPWStr)] System.Text.StringBuilder pszBuf,   // LPWSTR out
    [MarshalAs(UnmanagedType.LPWStr)] string pszPath   // LPCWSTR
);
<DllImport("SHLWAPI.dll", CharSet:=CharSet.Unicode, SetLastError:=True, ExactSpelling:=True)>
Public Shared Function PathCanonicalizeW(
    <MarshalAs(UnmanagedType.LPWStr)> pszBuf As System.Text.StringBuilder,   ' LPWSTR out
    <MarshalAs(UnmanagedType.LPWStr)> pszPath As String   ' LPCWSTR
) As <MarshalAs(UnmanagedType.Bool)> Boolean
End Function
' pszBuf : LPWSTR out
' pszPath : LPCWSTR
Declare PtrSafe Function PathCanonicalizeW Lib "shlwapi" ( _
    ByVal pszBuf As LongPtr, _
    ByVal pszPath As LongPtr) As Long
' Unicode(W): 文字列は ByVal As LongPtr とし StrPtr(unicodeStr) を渡す
' VBA7前提(PtrSafe)。32bit Office では LongPtr→Long。Integer=16bit / Long=32bit / LongLong=64bit。
import ctypes
from ctypes import wintypes

PathCanonicalizeW = ctypes.windll.shlwapi.PathCanonicalizeW
PathCanonicalizeW.restype = wintypes.BOOL
PathCanonicalizeW.argtypes = [
    wintypes.LPWSTR,  # pszBuf : LPWSTR out
    wintypes.LPCWSTR,  # pszPath : LPCWSTR
]
# GetLastError: use ctypes.GetLastError() (or ctypes.WinDLL(use_last_error=True))
require 'fiddle'
require 'fiddle/import'

lib = Fiddle.dlopen('SHLWAPI.dll')
PathCanonicalizeW = Fiddle::Function.new(
  lib['PathCanonicalizeW'],
  [
    Fiddle::TYPE_VOIDP,  # pszBuf : LPWSTR out
    Fiddle::TYPE_VOIDP,  # pszPath : LPCWSTR
  ],
  Fiddle::TYPE_INT)
# Wide strings: pass str.encode("UTF-16LE") + "\x00\x00"
#[link(name = "shlwapi")]
extern "system" {
    fn PathCanonicalizeW(
        pszBuf: *mut u16,  // LPWSTR out
        pszPath: *const u16  // LPCWSTR
    ) -> i32;
}
// crates: windows-sys provides ready-made bindings for this API.
$sig = @"
[return: MarshalAs(UnmanagedType.Bool)]
[DllImport("SHLWAPI.dll", CharSet = CharSet.Unicode, SetLastError = true)]
public static extern bool PathCanonicalizeW([MarshalAs(UnmanagedType.LPWStr)] System.Text.StringBuilder pszBuf, [MarshalAs(UnmanagedType.LPWStr)] string pszPath);
"@
$api = Add-Type -MemberDefinition $sig -Name 'SHLWAPI_PathCanonicalizeW' -Namespace Win32 -PassThru
# $api::PathCanonicalizeW(pszBuf, pszPath)
#uselib "SHLWAPI.dll"
#func global PathCanonicalizeW "PathCanonicalizeW" wptr, wptr
; PathCanonicalizeW varptr(pszBuf), pszPath   ; 戻り値は stat
; pszBuf : LPWSTR out -> "wptr"
; pszPath : LPCWSTR -> "wptr"
; ※HSP3.7は #func のため戻り値はシステム変数 stat に格納されます。
出力引数:
#uselib "SHLWAPI.dll"
#cfunc global PathCanonicalizeW "PathCanonicalizeW" var, wstr
; res = PathCanonicalizeW(pszBuf, pszPath)
; pszBuf : LPWSTR out -> "var"
; pszPath : LPCWSTR -> "wstr"
; ※出力/バッファ引数は var 方式(変数を直接渡す)。varptr 方式にも切替可。
出力引数:
; BOOL PathCanonicalizeW(LPWSTR pszBuf, LPCWSTR pszPath)
#uselib "SHLWAPI.dll"
#cfunc global PathCanonicalizeW "PathCanonicalizeW" var, wstr
; res = PathCanonicalizeW(pszBuf, pszPath)
; pszBuf : LPWSTR out -> "var"
; pszPath : LPCWSTR -> "wstr"
; ※出力/バッファ引数は var 方式(変数を直接渡す)。varptr 方式にも切替可。
import (
	"golang.org/x/sys/windows"
	"unsafe"
)

var (
	shlwapi = windows.NewLazySystemDLL("SHLWAPI.dll")
	procPathCanonicalizeW = shlwapi.NewProc("PathCanonicalizeW")
)

// pszBuf (LPWSTR out), pszPath (LPCWSTR)
r1, _, err := procPathCanonicalizeW.Call(
	uintptr(pszBuf),
	uintptr(unsafe.Pointer(windows.StringToUTF16Ptr(pszPath))),
)
_ = err  // syscall.Errno (valid when the call sets last-error)
_ = r1   // BOOL
function PathCanonicalizeW(
  pszBuf: PWideChar;   // LPWSTR out
  pszPath: PWideChar   // LPCWSTR
): BOOL; stdcall;
  external 'SHLWAPI.dll' name 'PathCanonicalizeW';
result := DllCall("SHLWAPI\PathCanonicalizeW"
    , "Ptr", pszBuf   ; LPWSTR out
    , "WStr", pszPath   ; LPCWSTR
    , "Int")   ; return: BOOL
●PathCanonicalizeW(pszBuf, pszPath) = DLL("SHLWAPI.dll", "bool PathCanonicalizeW(char*, char*)")
# 呼び出し: PathCanonicalizeW(pszBuf, pszPath)
# pszBuf : LPWSTR out -> "char*"
# pszPath : LPCWSTR -> "char*"
# なでしこ1は32bit・ANSI(Shift_JIS)。文字列=char*(ANSI)、ポインタ/ハンドル=void*(4byte)。
# ※-W(Unicode)関数。なでしこ1はANSIのため -A 版の利用を推奨。
const std = @import("std");

extern "shlwapi" fn PathCanonicalizeW(
    pszBuf: [*c]u16, // LPWSTR out
    pszPath: [*c]const u16 // LPCWSTR
) callconv(std.os.windows.WINAPI) i32;
// Unicode(-W): UTF-16LE のヌル終端バッファ([*c]const u16)を渡す。
proc PathCanonicalizeW(
    pszBuf: ptr uint16,  # LPWSTR out
    pszPath: WideCString  # LPCWSTR
): int32 {.importc: "PathCanonicalizeW", stdcall, dynlib: "SHLWAPI.dll".}
# Unicode(-W): WideCString は newWideCString("...") で生成。
pragma(lib, "shlwapi");
extern(Windows)
int PathCanonicalizeW(
    wchar* pszBuf,   // LPWSTR out
    const(wchar)* pszPath   // LPCWSTR
);
ccall((:PathCanonicalizeW, "SHLWAPI.dll"), stdcall, Int32,
      (Ptr{UInt16}, Cwstring),
      pszBuf, pszPath)
# pszBuf : LPWSTR out -> Ptr{UInt16}
# pszPath : LPCWSTR -> Cwstring
# stdcall は 32bit のみ意味を持つ(x64 では無視)。
# Unicode(-W): Cwstring には transcode(UInt16, "...") 等で UTF-16 を渡す。
local ffi = require("ffi")
ffi.cdef[[
int32_t PathCanonicalizeW(
    uint16_t* pszBuf,
    const uint16_t* pszPath);
]]
local shlwapi = ffi.load("shlwapi")
-- shlwapi.PathCanonicalizeW(pszBuf, pszPath)
-- pszBuf : LPWSTR out
-- pszPath : LPCWSTR
-- 構造体/GUIDへのポインタは cdef が通るよう void* で表記(実型は各引数コメント参照)。値渡し構造体・enum は対応する typedef を cdef に追加すること。
-- Unicode(-W): uint16_t* には UTF-16LE のバッファ(ffi.new("uint16_t[?]", ...))を渡す。
const koffi = require('koffi');
const lib = koffi.load('SHLWAPI.dll');
const PathCanonicalizeW = lib.func('__stdcall', 'PathCanonicalizeW', 'int32_t', ['uint16_t *', 'str16']);
// PathCanonicalizeW(pszBuf, pszPath)
// pszBuf : LPWSTR out -> 'uint16_t *'
// pszPath : LPCWSTR -> 'str16'
// 出力ポインタは koffi.out(...) で包む。構造体は koffi.struct で定義。
const lib = Deno.dlopen("SHLWAPI.dll", {
  PathCanonicalizeW: { parameters: ["buffer", "buffer"], result: "i32" },
});
// lib.symbols.PathCanonicalizeW(pszBuf, pszPath)
// pszBuf : LPWSTR out -> "buffer"
// pszPath : LPCWSTR -> "buffer"
// 文字列は "buffer"。Unicode(-W) は new TextEncoder() ではなく UTF-16LE のバイト列(末尾に \x00\x00)を Uint8Array で渡す。
// 値渡し構造体は { struct: [ ...field types... ] } を使用。
<?php
$ffi = FFI::cdef(<<<C
int32_t PathCanonicalizeW(
    uint16_t* pszBuf,
    const uint16_t* pszPath);
C, "SHLWAPI.dll");
// $ffi->PathCanonicalizeW(pszBuf, pszPath);
// pszBuf : LPWSTR out
// pszPath : LPCWSTR
// 構造体/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 Shlwapi extends StdCallLibrary {
    Shlwapi INSTANCE = Native.load("shlwapi", Shlwapi.class, W32APIOptions.UNICODE_OPTIONS);
    boolean PathCanonicalizeW(
        char[] pszBuf,   // LPWSTR out
        WString pszPath   // LPCWSTR
    );
}
// Unicode(-W): WString(入力)/char[](出力)で UTF-16 をマーシャリング。
@[Link("shlwapi")]
lib LibSHLWAPI
  fun PathCanonicalizeW = PathCanonicalizeW(
    pszBuf : UInt16*,   # LPWSTR out
    pszPath : UInt16*   # LPCWSTR
  ) : Int32
end
# 構造体/GUID/enum は lib 内に対応する型定義が必要。
# 呼出規約: x64 は規約統一のため OK。x86(32bit)は WINAPI=stdcall だが Crystal の fun に stdcall 付与構文がなく非対応。
import 'dart:ffi';
import 'package:ffi/ffi.dart';

typedef PathCanonicalizeWNative = Int32 Function(Pointer<Utf16>, Pointer<Utf16>);
typedef PathCanonicalizeWDart = int Function(Pointer<Utf16>, Pointer<Utf16>);
final PathCanonicalizeW = DynamicLibrary.open('SHLWAPI.dll')
    .lookupFunction<PathCanonicalizeWNative, PathCanonicalizeWDart>('PathCanonicalizeW');
// pszBuf : LPWSTR out -> Pointer<Utf16>
// pszPath : LPCWSTR -> Pointer<Utf16>
// 文字列は package:ffi の "...".toNativeUtf16()/toNativeUtf8() で変換。
{$mode objfpc}{$H+}
function PathCanonicalizeW(
  pszBuf: PWideChar;   // LPWSTR out
  pszPath: PWideChar   // LPCWSTR
): BOOL; stdcall;
  external 'SHLWAPI.dll' name 'PathCanonicalizeW';
import Foreign
import Foreign.C.Types
import Foreign.C.String

foreign import stdcall safe "PathCanonicalizeW"
  c_PathCanonicalizeW :: CWString -> CWString -> IO CInt
-- pszBuf : LPWSTR out -> CWString
-- pszPath : LPCWSTR -> CWString
-- 要 GHC(Windows)。stdcall は x64 では ccall として扱われる。ブロックする API は safe 呼び出し推奨。
open Ctypes
open Foreign

let pathcanonicalizew =
  foreign "PathCanonicalizeW"
    ((ptr uint16_t) @-> (ptr uint16_t) @-> returning int32_t)
(* pszBuf : LPWSTR out -> (ptr uint16_t) *)
(* pszPath : LPCWSTR -> (ptr uint16_t) *)
(* foreign は cdecl 前提。x64 Windows では WINAPI と一致。構造体は ctypes structure を定義のこと。 *)
(cffi:define-foreign-library shlwapi (t "SHLWAPI.dll"))
(cffi:use-foreign-library shlwapi)

(cffi:defcfun ("PathCanonicalizeW" path-canonicalize-w :convention :stdcall) :int32
  (psz-buf :pointer)   ; LPWSTR out
  (psz-path (:string :encoding :utf-16le)))   ; LPCWSTR
; isize/usize(INT_PTR/SIZE_T)は x64 前提で :int64/:uint64。x86 では :int32/:uint32。
use Win32::API;
my $PathCanonicalizeW = Win32::API::More->new('SHLWAPI',
    'BOOL PathCanonicalizeW(LPWSTR pszBuf, LPCWSTR pszPath)');
# my $ret = $PathCanonicalizeW->Call($pszBuf, $pszPath);
# pszBuf : LPWSTR out -> LPWSTR
# pszPath : LPCWSTR -> LPCWSTR
# 値渡し構造体は pack() した文字列、または Win32::API::Struct を使用。
# Unicode(-W): LPCWSTR/LPWSTR は Win32::API が UTF-16 変換を行う。

関連項目

文字セット違い