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

PathRelativePathToW

関数
ある場所から別の場所への相対パスを生成する。
DLLSHLWAPI.dll文字セットUnicode (-W)呼出規約winapi対応OSWindows 2000 以降

シグネチャ

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

BOOL PathRelativePathToW(
    LPWSTR pszPath,
    LPCWSTR pszFrom,
    DWORD dwAttrFrom,
    LPCWSTR pszTo,
    DWORD dwAttrTo
);

パラメーター

名前方向説明
pszPathLPWSTRout相対パスを受け取る文字列へのポインター。このバッファーは少なくとも MAX_PATH 文字分のサイズが必要です。
pszFromLPCWSTRin相対パスの起点を定義するパスを格納した、最大長 MAX_PATH の null 終端文字列へのポインター。
dwAttrFromDWORDinpszFrom のファイル属性。この値に FILE_ATTRIBUTE_DIRECTORY が含まれている場合、pszFrom はディレクトリと見なされます。それ以外の場合、pszFrom はファイルと見なされます。
pszToLPCWSTRin相対パスの終点を定義するパスを格納した、最大長 MAX_PATH の null 終端文字列へのポインター。
dwAttrToDWORDinpszTo のファイル属性。この値に FILE_ATTRIBUTE_DIRECTORY が含まれている場合、pszTo はディレクトリと見なされます。それ以外の場合、pszTo はファイルと見なされます。

戻り値の型: BOOL

公式ドキュメント

あるファイルまたはフォルダーから別のファイルまたはフォルダーへの相対パスを作成します。(Unicode)

戻り値

型: BOOL

成功した場合は TRUE を、それ以外の場合は FALSE を返します。

解説(Remarks)

この関数は 1 組のパスを受け取り、一方から他方への相対パスを生成します。パスは完全修飾されている必要はありませんが、共通の接頭辞を持っている必要があります。持っていない場合、この関数は失敗して FALSE を返します。

たとえば、起点 pszFrom を "c:\FolderA\FolderB\FolderC"、終点 pszTo を "c:\FolderA\FolderD\FolderE" とします。PathRelativePathTopszFrom から pszTo への相対パスとして "....\FolderD\FolderE" を返します。pszFrom を "\FolderA\FolderB\FolderC"、pszTo を "\FolderA\FolderD\FolderE" に設定した場合も同じ結果になります。一方、"c:\FolderA\FolderB" と "a:\FolderA\FolderD" は共通の接頭辞を持たないため、この関数は失敗します。なお、"\" は接頭辞とは見なされず、無視されます。pszFrom を "\FolderA\FolderB"、pszTo を "\FolderC\FolderD" に設定した場合、この関数は失敗します。

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

void main(void)
{
    char szOut[MAX_PATH] = "";
    char szFrom[ ] = "c:\\a\\b\\path";
    char szTo[ ] = "c:\\a\\x\\y\\file";

    cout  <<  "The relative path is relative from: ";
    cout  <<  szFrom;
    cout  <<  "\n";

    cout  <<  "The relative path is relative to: ";
    cout  <<  szTo;
    cout  <<  "\n";

    PathRelativePathTo(szOut,
                       szFrom,
                       FILE_ATTRIBUTE_DIRECTORY,
                       szTo,
                       FILE_ATTRIBUTE_NORMAL);

    cout  <<  "The relative path is: ";
    cout  <<  szOut;
    cout  <<  "\n";
}

OUTPUT:
==================
The relative path is relative from: c:\a\b\path
The relative path is relative to: c:\a\x\y\file
The relative path is: ..\..\x\y\file
メモ

shlwapi.h ヘッダーは PathRelativePathTo をエイリアスとして定義しており、UNICODE プリプロセッサ定数の定義に基づいて、この関数の ANSI 版または Unicode 版を自動的に選択します。エンコーディング非依存のエイリアスを、エンコーディング非依存でないコードと混在して使用すると、不一致が生じ、コンパイルエラーまたは実行時エラーを引き起こす可能性があります。詳細については、関数プロトタイプの規則を参照してください。

出典・ライセンス: 上記「公式ドキュメント」の内容は 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 PathRelativePathToW(
    LPWSTR pszPath,
    LPCWSTR pszFrom,
    DWORD dwAttrFrom,
    LPCWSTR pszTo,
    DWORD dwAttrTo
);
[return: MarshalAs(UnmanagedType.Bool)]
[DllImport("SHLWAPI.dll", CharSet = CharSet.Unicode, ExactSpelling = true)]
static extern bool PathRelativePathToW(
    [MarshalAs(UnmanagedType.LPWStr)] System.Text.StringBuilder pszPath,   // LPWSTR out
    [MarshalAs(UnmanagedType.LPWStr)] string pszFrom,   // LPCWSTR
    uint dwAttrFrom,   // DWORD
    [MarshalAs(UnmanagedType.LPWStr)] string pszTo,   // LPCWSTR
    uint dwAttrTo   // DWORD
);
<DllImport("SHLWAPI.dll", CharSet:=CharSet.Unicode, ExactSpelling:=True)>
Public Shared Function PathRelativePathToW(
    <MarshalAs(UnmanagedType.LPWStr)> pszPath As System.Text.StringBuilder,   ' LPWSTR out
    <MarshalAs(UnmanagedType.LPWStr)> pszFrom As String,   ' LPCWSTR
    dwAttrFrom As UInteger,   ' DWORD
    <MarshalAs(UnmanagedType.LPWStr)> pszTo As String,   ' LPCWSTR
    dwAttrTo As UInteger   ' DWORD
) As <MarshalAs(UnmanagedType.Bool)> Boolean
End Function
' pszPath : LPWSTR out
' pszFrom : LPCWSTR
' dwAttrFrom : DWORD
' pszTo : LPCWSTR
' dwAttrTo : DWORD
Declare PtrSafe Function PathRelativePathToW Lib "shlwapi" ( _
    ByVal pszPath As LongPtr, _
    ByVal pszFrom As LongPtr, _
    ByVal dwAttrFrom As Long, _
    ByVal pszTo As LongPtr, _
    ByVal dwAttrTo As Long) 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

PathRelativePathToW = ctypes.windll.shlwapi.PathRelativePathToW
PathRelativePathToW.restype = wintypes.BOOL
PathRelativePathToW.argtypes = [
    wintypes.LPWSTR,  # pszPath : LPWSTR out
    wintypes.LPCWSTR,  # pszFrom : LPCWSTR
    wintypes.DWORD,  # dwAttrFrom : DWORD
    wintypes.LPCWSTR,  # pszTo : LPCWSTR
    wintypes.DWORD,  # dwAttrTo : DWORD
]
require 'fiddle'
require 'fiddle/import'

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

var (
	shlwapi = windows.NewLazySystemDLL("SHLWAPI.dll")
	procPathRelativePathToW = shlwapi.NewProc("PathRelativePathToW")
)

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

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

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

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

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

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

関連項目

文字セット違い