VirtualAlloc2
関数シグネチャ
// api-ms-win-core-memory-l1-1-6.dll
#include <windows.h>
void* VirtualAlloc2(
HANDLE Process, // optional
void* BaseAddress, // optional
UINT_PTR Size,
VIRTUAL_ALLOCATION_TYPE AllocationType,
DWORD PageProtection,
MEM_EXTENDED_PARAMETER* ExtendedParameters, // optional
DWORD ParameterCount
);パラメーター
| 名前 | 型 | 方向 | 説明 | ||||||||||||||||||||||||
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
| Process | HANDLE | inoptional | プロセスのハンドル。この関数は、このプロセスの仮想アドレス空間内にメモリを割り当てます。 ハンドルには PROCESS_VM_OPERATION アクセス権が必要です。詳細については、Process Security and Access Rights を参照してください。 Process が NULL の場合、この関数は呼び出し元プロセスにメモリを割り当てます。 | ||||||||||||||||||||||||
| BaseAddress | void* | inoptional | 割り当てたいページ領域の開始アドレスとして希望する値を指定するポインター。 BaseAddress が NULL の場合、関数が領域を割り当てる場所を決定します。 BaseAddress が NULL でない場合、指定する MEM_ADDRESS_REQUIREMENTS 構造体はすべてゼロでなければならず、ベースアドレスはシステムの割り当て粒度の倍数でなければなりません。割り当て粒度を取得するには、GetSystemInfo 関数を使用します。 このアドレスが、InitializeEnclave を呼び出して初期化していないエンクレーブ内にある場合、VirtualAlloc2 はそのアドレスのエンクレーブに対してゼロのページを割り当てます。そのページは事前にアンコミット状態でなければならず、Intel Software Guard Extensions プログラミングモデルの EEXTEND 命令によって計測されることはありません。 アドレスが、初期化済みのエンクレーブ内にある場合、割り当て操作は ERROR_INVALID_ADDRESS エラーで失敗します。これは動的メモリ管理をサポートしないエンクレーブ(すなわち SGX1)に当てはまります。SGX2 エンクレーブでは割り当てが許可されますが、割り当て後にそのページはエンクレーブによって受け入れられる必要があります。 | ||||||||||||||||||||||||
| Size | UINT_PTR | in | 割り当てるメモリ領域のサイズ(バイト単位)。 サイズは常にページサイズの倍数でなければなりません。 BaseAddress が NULL でない場合、この関数は BaseAddress から BaseAddress+Size までの範囲に 1 バイト以上を含むすべてのページを割り当てます。つまり、たとえばページ境界をまたぐ 2 バイトの範囲を指定すると、関数は両方のページを割り当てます。 | ||||||||||||||||||||||||
| AllocationType | VIRTUAL_ALLOCATION_TYPE | in | メモリ割り当ての種類。このパラメーターには次のいずれかの値を含める必要があります。
このパラメーターには、以下に示す値も指定できます。
| ||||||||||||||||||||||||
| PageProtection | DWORD | in | 割り当てるページ領域のメモリ保護。ページをコミットする場合は、メモリ保護定数のいずれか 1 つを指定できます。 BaseAddress がエンクレーブ内のアドレスを指定する場合、PageProtection には次の値を指定できません。 エンクレーブ用に動的メモリを割り当てる場合、PageProtection パラメーターは PAGE_READWRITE または PAGE_EXECUTE_READWRITE でなければなりません。 | ||||||||||||||||||||||||
| ExtendedParameters | MEM_EXTENDED_PARAMETER* | inoutoptional | MEM_EXTENDED_PARAMETER 型の 1 つ以上の拡張パラメーターへの省略可能なポインター。これらの拡張パラメーター値はそれぞれ、MemExtendedParameterAddressRequirements または MemExtendedParameterNumaNode のいずれかの Type フィールドを持つことができます。MemExtendedParameterNumaNode 拡張パラメーターが指定されていない場合の動作は、VirtualAlloc/MapViewOfFile 関数と同じです(つまり、物理ページの優先 NUMA ノードは、そのメモリに最初にアクセスするスレッドの理想プロセッサに基づいて決定されます)。 | ||||||||||||||||||||||||
| ParameterCount | DWORD | in | ExtendedParameters が指す拡張パラメーターの数。 |
戻り値の型: void*
公式ドキュメント
指定したプロセスの仮想アドレス空間内のメモリ領域を予約、コミット、または状態変更します。この関数は割り当てたメモリをゼロで初期化します。(VirtualAlloc2)
戻り値
関数が成功した場合、戻り値は割り当てられたページ領域のベースアドレスです。
関数が失敗した場合、戻り値は NULL です。拡張エラー情報を取得するには、GetLastError を呼び出します。
解説(Remarks)
この関数では次の指定が可能です。
- 新規割り当てに対する仮想アドレス空間の範囲と 2 のべき乗のアラインメント制約
- 任意の数の拡張パラメーター
- 拡張パラメーターとしての物理メモリの優先 NUMA ノード(ExtendedParameters パラメーターを参照)
- プレースホルダー操作(具体的には置き換え)。
この API は、高性能なゲームやサーバーアプリケーションをサポートするために、仮想メモリを管理する特殊な手法を提供します。たとえば、プレースホルダーを使用すると、予約済みメモリ範囲を明示的に分割、オーバーレイ、再マップでき、任意に拡張可能な領域や仮想メモリのリングバッファの実装に利用できます。また、VirtualAlloc2 では特定のメモリアラインメントでメモリを割り当てることもできます。
各ページには、関連付けられたページ状態があります。VirtualAlloc2 関数は次の操作を実行できます。
- 予約済みページの領域をコミットする
- 空きページの領域を予約する
- 空きページの領域を同時に予約してコミットする
VirtualAlloc2 はすでにコミット済みのページをコミットできますが、すでに予約済みのページを予約することはできません。これは、ページがすでにコミットされているかどうかにかかわらずページ範囲をコミットでき、関数が失敗しないことを意味します。ただし一般的には、すでにコミット済みのページを大量にコミットすると VirtualAlloc2 の呼び出しに非常に長い時間がかかる可能性があるため、ほとんどがアンコミットの最小限の範囲のみを指定すべきです。
VirtualAlloc2 を使用して一連のページを予約し、その後 VirtualAlloc2 を追加で呼び出して、予約済みブロックから個々のページをコミットできます。これにより、プロセスは必要になるまで物理ストレージを消費せずに仮想アドレス空間の範囲を予約できます。
lpAddress パラメーターが NULL でない場合、関数は lpAddress と dwSize パラメーターを使用して割り当てるページ領域を計算します。ページ範囲全体の現在の状態は、flAllocationType パラメーターで指定した割り当ての種類と互換性がなければなりません。そうでない場合、関数は失敗し、どのページも割り当てられません。この互換性要件は、すでにコミット済みのページをコミットすることを妨げるものではありません。前述の一覧を参照してください。
動的に生成したコードを実行するには、VirtualAlloc2 を使用してメモリを割り当て、VirtualProtectEx 関数を使用して PAGE_EXECUTE アクセスを付与します。
VirtualAlloc2 関数を使用すると、指定したプロセスの仮想アドレス空間内に Address Windowing Extensions(AWE)領域のメモリを予約できます。このメモリ領域は、その後アプリケーションの必要に応じて物理ページを仮想メモリにマップ/アンマップするために使用できます。AllocationType パラメーターには MEM_PHYSICAL と MEM_RESERVE の値を設定する必要があります。MEM_COMMIT の値は設定してはなりません。ページ保護は PAGE_READWRITE に設定する必要があります。
VirtualFreeEx 関数は、コミット済みのページをデコミットしてそのページのストレージを解放したり、コミット済みのページを同時にデコミットして解放したりできます。また、予約済みのページを解放して空きページにすることもできます。
実行可能となる領域を作成する場合、コードを配置した後に FlushInstructionCache を適切に呼び出してキャッシュの一貫性を確保する責任は、呼び出し元プログラムにあります。そうしないと、新たに実行可能となった領域からコードを実行しようとしたときに予測不能な結果を生じる可能性があります。
Examples
シナリオ 1。同じ共有メモリセクションの隣接する 2 つのビューをマップして循環バッファを作成します。
#include <windows.h>
#include <stdio.h>
#include <stdlib.h>
//
// This function creates a ring buffer by allocating a pagefile-backed section
// and mapping two views of that section next to each other. This way if the
// last record in the buffer wraps it can still be accessed in a linear fashion
// using its base VA.
//
void*
CreateRingBuffer (
unsigned int bufferSize,
_Outptr_ void** secondaryView
)
{
BOOL result;
HANDLE section = nullptr;
SYSTEM_INFO sysInfo;
void* ringBuffer = nullptr;
void* placeholder1 = nullptr;
void* placeholder2 = nullptr;
void* view1 = nullptr;
void* view2 = nullptr;
GetSystemInfo (&sysInfo);
if ((bufferSize % sysInfo.dwAllocationGranularity) != 0) {
return nullptr;
}
//
// Reserve a placeholder region where the buffer will be mapped.
//
placeholder1 = (PCHAR) VirtualAlloc2 (
nullptr,
nullptr,
2 * bufferSize,
MEM_RESERVE | MEM_RESERVE_PLACEHOLDER,
PAGE_NOACCESS,
nullptr, 0
);
if (placeholder1 == nullptr) {
printf ("VirtualAlloc2 failed, error %#x\n", GetLastError());
goto Exit;
}
//
// Split the placeholder region into two regions of equal size.
//
result = VirtualFree (
placeholder1,
bufferSize,
MEM_RELEASE | MEM_PRESERVE_PLACEHOLDER
);
if (result == FALSE) {
printf ("VirtualFreeEx failed, error %#x\n", GetLastError());
goto Exit;
}
placeholder2 = (void*) ((ULONG_PTR) placeholder1 + bufferSize);
//
// Create a pagefile-backed section for the buffer.
//
section = CreateFileMapping (
INVALID_HANDLE_VALUE,
nullptr,
PAGE_READWRITE,
0,
bufferSize, nullptr
);
if (section == nullptr) {
printf ("CreateFileMapping failed, error %#x\n", GetLastError());
goto Exit;
}
//
// Map the section into the first placeholder region.
//
view1 = MapViewOfFile3 (
section,
nullptr,
placeholder1,
0,
bufferSize,
MEM_REPLACE_PLACEHOLDER,
PAGE_READWRITE,
nullptr, 0
);
if (view1 == nullptr) {
printf ("MapViewOfFile3 failed, error %#x\n", GetLastError());
goto Exit;
}
//
// Ownership transferred, don't free this now.
//
placeholder1 = nullptr;
//
// Map the section into the second placeholder region.
//
view2 = MapViewOfFile3 (
section,
nullptr,
placeholder2,
0,
bufferSize,
MEM_REPLACE_PLACEHOLDER,
PAGE_READWRITE,
nullptr, 0
);
if (view2 == nullptr) {
printf ("MapViewOfFile3 failed, error %#x\n", GetLastError());
goto Exit;
}
//
// Success, return both mapped views to the caller.
//
ringBuffer = view1;
*secondaryView = view2;
placeholder2 = nullptr;
view1 = nullptr;
view2 = nullptr;
Exit:
if (section != nullptr) {
CloseHandle (section);
}
if (placeholder1 != nullptr) {
VirtualFree (placeholder1, 0, MEM_RELEASE);
}
if (placeholder2 != nullptr) {
VirtualFree (placeholder2, 0, MEM_RELEASE);
}
if (view1 != nullptr) {
UnmapViewOfFileEx (view1, 0);
}
if (view2 != nullptr) {
UnmapViewOfFileEx (view2, 0);
}
return ringBuffer;
}
int __cdecl wmain()
{
char* ringBuffer;
void* secondaryView;
unsigned int bufferSize = 0x10000;
ringBuffer = (char*) CreateRingBuffer (bufferSize, &secondaryView);
if (ringBuffer == nullptr) {
printf ("CreateRingBuffer failed\n");
return 0;
}
//
// Make sure the buffer wraps properly.
//
ringBuffer[0] = 'a';
if (ringBuffer[bufferSize] == 'a') {
printf ("The buffer wraps as expected\n");
}
UnmapViewOfFile (ringBuffer);
UnmapViewOfFile (secondaryView);
}
シナリオ 2。メモリ割り当て時に優先 NUMA ノードを指定します。
void*
AllocateWithPreferredNode (size_t size, unsigned int numaNode)
{
MEM_EXTENDED_PARAMETER param = {0};
param.Type = MemExtendedParameterNumaNode;
param.ULong = numaNode;
return VirtualAlloc2 (
nullptr, nullptr,
size,
MEM_RESERVE | MEM_COMMIT,
PAGE_READWRITE,
¶m, 1);
}
シナリオ 3。特定の仮想アドレス範囲(この例では 4GB 未満)かつ特定のアラインメントでメモリを割り当てます。
void*
AllocateAlignedBelow2GB (size_t size, size_t alignment)
{
MEM_ADDRESS_REQUIREMENTS addressReqs = {0};
MEM_EXTENDED_PARAMETER param = {0};
addressReqs.Alignment = alignment;
addressReqs.HighestEndingAddress = (PVOID)(ULONG_PTR) 0x7fffffff;
param.Type = MemExtendedParameterAddressRequirements;
param.Pointer = &addressReqs;
return VirtualAlloc2 (
nullptr, nullptr,
size,
MEM_RESERVE | MEM_COMMIT,
PAGE_READWRITE,
¶m, 1);
}
Microsoft 公式リファレンス: 英語 (en-us) · 日本語 (ja-jp) · 原文ソース (GitHub)
各言語での呼び出し定義
// api-ms-win-core-memory-l1-1-6.dll
#include <windows.h>
void* VirtualAlloc2(
HANDLE Process, // optional
void* BaseAddress, // optional
UINT_PTR Size,
VIRTUAL_ALLOCATION_TYPE AllocationType,
DWORD PageProtection,
MEM_EXTENDED_PARAMETER* ExtendedParameters, // optional
DWORD ParameterCount
);[DllImport("api-ms-win-core-memory-l1-1-6.dll", SetLastError = true, ExactSpelling = true)]
static extern IntPtr VirtualAlloc2(
IntPtr Process, // HANDLE optional
IntPtr BaseAddress, // void* optional
UIntPtr Size, // UINT_PTR
uint AllocationType, // VIRTUAL_ALLOCATION_TYPE
uint PageProtection, // DWORD
IntPtr ExtendedParameters, // MEM_EXTENDED_PARAMETER* optional, in/out
uint ParameterCount // DWORD
);<DllImport("api-ms-win-core-memory-l1-1-6.dll", SetLastError:=True, ExactSpelling:=True)>
Public Shared Function VirtualAlloc2(
Process As IntPtr, ' HANDLE optional
BaseAddress As IntPtr, ' void* optional
Size As UIntPtr, ' UINT_PTR
AllocationType As UInteger, ' VIRTUAL_ALLOCATION_TYPE
PageProtection As UInteger, ' DWORD
ExtendedParameters As IntPtr, ' MEM_EXTENDED_PARAMETER* optional, in/out
ParameterCount As UInteger ' DWORD
) As IntPtr
End Function' Process : HANDLE optional
' BaseAddress : void* optional
' Size : UINT_PTR
' AllocationType : VIRTUAL_ALLOCATION_TYPE
' PageProtection : DWORD
' ExtendedParameters : MEM_EXTENDED_PARAMETER* optional, in/out
' ParameterCount : DWORD
Declare PtrSafe Function VirtualAlloc2 Lib "api-ms-win-core-memory-l1-1-6" ( _
ByVal Process As LongPtr, _
ByVal BaseAddress As LongPtr, _
ByVal Size As LongPtr, _
ByVal AllocationType As Long, _
ByVal PageProtection As Long, _
ByVal ExtendedParameters As LongPtr, _
ByVal ParameterCount As Long) As LongPtr
' VBA7前提(PtrSafe)。32bit Office では LongPtr→Long。Integer=16bit / Long=32bit / LongLong=64bit。import ctypes
from ctypes import wintypes
VirtualAlloc2 = ctypes.windll.LoadLibrary("api-ms-win-core-memory-l1-1-6.dll").VirtualAlloc2
VirtualAlloc2.restype = ctypes.c_void_p
VirtualAlloc2.argtypes = [
wintypes.HANDLE, # Process : HANDLE optional
ctypes.POINTER(None), # BaseAddress : void* optional
ctypes.c_size_t, # Size : UINT_PTR
wintypes.DWORD, # AllocationType : VIRTUAL_ALLOCATION_TYPE
wintypes.DWORD, # PageProtection : DWORD
ctypes.c_void_p, # ExtendedParameters : MEM_EXTENDED_PARAMETER* optional, in/out
wintypes.DWORD, # ParameterCount : DWORD
]
# GetLastError: use ctypes.GetLastError() (or ctypes.WinDLL(use_last_error=True))require 'fiddle'
require 'fiddle/import'
lib = Fiddle.dlopen('api-ms-win-core-memory-l1-1-6.dll')
VirtualAlloc2 = Fiddle::Function.new(
lib['VirtualAlloc2'],
[
Fiddle::TYPE_VOIDP, # Process : HANDLE optional
Fiddle::TYPE_VOIDP, # BaseAddress : void* optional
Fiddle::TYPE_UINTPTR_T, # Size : UINT_PTR
-Fiddle::TYPE_INT, # AllocationType : VIRTUAL_ALLOCATION_TYPE
-Fiddle::TYPE_INT, # PageProtection : DWORD
Fiddle::TYPE_VOIDP, # ExtendedParameters : MEM_EXTENDED_PARAMETER* optional, in/out
-Fiddle::TYPE_INT, # ParameterCount : DWORD
],
Fiddle::TYPE_VOIDP)#[link(name = "api-ms-win-core-memory-l1-1-6")]
extern "system" {
fn VirtualAlloc2(
Process: *mut core::ffi::c_void, // HANDLE optional
BaseAddress: *mut (), // void* optional
Size: usize, // UINT_PTR
AllocationType: u32, // VIRTUAL_ALLOCATION_TYPE
PageProtection: u32, // DWORD
ExtendedParameters: *mut MEM_EXTENDED_PARAMETER, // MEM_EXTENDED_PARAMETER* optional, in/out
ParameterCount: u32 // DWORD
) -> *mut ();
}
// crates: windows-sys provides ready-made bindings for this API.$sig = @"
[DllImport("api-ms-win-core-memory-l1-1-6.dll", SetLastError = true)]
public static extern IntPtr VirtualAlloc2(IntPtr Process, IntPtr BaseAddress, UIntPtr Size, uint AllocationType, uint PageProtection, IntPtr ExtendedParameters, uint ParameterCount);
"@
$api = Add-Type -MemberDefinition $sig -Name 'api-ms-win-core-memory-l1-1-6_VirtualAlloc2' -Namespace Win32 -PassThru
# $api::VirtualAlloc2(Process, BaseAddress, Size, AllocationType, PageProtection, ExtendedParameters, ParameterCount)#uselib "api-ms-win-core-memory-l1-1-6.dll"
#func global VirtualAlloc2 "VirtualAlloc2" sptr, sptr, sptr, sptr, sptr, sptr, sptr
; VirtualAlloc2 Process, BaseAddress, Size, AllocationType, PageProtection, varptr(ExtendedParameters), ParameterCount ; 戻り値は stat
; Process : HANDLE optional -> "sptr"
; BaseAddress : void* optional -> "sptr"
; Size : UINT_PTR -> "sptr"
; AllocationType : VIRTUAL_ALLOCATION_TYPE -> "sptr"
; PageProtection : DWORD -> "sptr"
; ExtendedParameters : MEM_EXTENDED_PARAMETER* optional, in/out -> "sptr"
; ParameterCount : DWORD -> "sptr"
; ※HSP3.7は #func のため戻り値はシステム変数 stat に格納されます。#uselib "api-ms-win-core-memory-l1-1-6.dll" #cfunc global VirtualAlloc2 "VirtualAlloc2" sptr, sptr, sptr, int, int, var, int ; res = VirtualAlloc2(Process, BaseAddress, Size, AllocationType, PageProtection, ExtendedParameters, ParameterCount) ; Process : HANDLE optional -> "sptr" ; BaseAddress : void* optional -> "sptr" ; Size : UINT_PTR -> "sptr" ; AllocationType : VIRTUAL_ALLOCATION_TYPE -> "int" ; PageProtection : DWORD -> "int" ; ExtendedParameters : MEM_EXTENDED_PARAMETER* optional, in/out -> "var" ; ParameterCount : DWORD -> "int" ; ※出力/バッファ引数は var 方式(変数を直接渡す)。varptr 方式にも切替可。#uselib "api-ms-win-core-memory-l1-1-6.dll" #cfunc global VirtualAlloc2 "VirtualAlloc2" sptr, sptr, sptr, int, int, sptr, int ; res = VirtualAlloc2(Process, BaseAddress, Size, AllocationType, PageProtection, varptr(ExtendedParameters), ParameterCount) ; Process : HANDLE optional -> "sptr" ; BaseAddress : void* optional -> "sptr" ; Size : UINT_PTR -> "sptr" ; AllocationType : VIRTUAL_ALLOCATION_TYPE -> "int" ; PageProtection : DWORD -> "int" ; ExtendedParameters : MEM_EXTENDED_PARAMETER* optional, in/out -> "sptr" ; ParameterCount : DWORD -> "int" ; ※出力/バッファ引数はポインタ方式(token=sptr / 呼び出しは varptr(変数))。
; void* VirtualAlloc2(HANDLE Process, void* BaseAddress, UINT_PTR Size, VIRTUAL_ALLOCATION_TYPE AllocationType, DWORD PageProtection, MEM_EXTENDED_PARAMETER* ExtendedParameters, DWORD ParameterCount) #uselib "api-ms-win-core-memory-l1-1-6.dll" #cfunc global VirtualAlloc2 "VirtualAlloc2" intptr, intptr, intptr, int, int, var, int ; res = VirtualAlloc2(Process, BaseAddress, Size, AllocationType, PageProtection, ExtendedParameters, ParameterCount) ; Process : HANDLE optional -> "intptr" ; BaseAddress : void* optional -> "intptr" ; Size : UINT_PTR -> "intptr" ; AllocationType : VIRTUAL_ALLOCATION_TYPE -> "int" ; PageProtection : DWORD -> "int" ; ExtendedParameters : MEM_EXTENDED_PARAMETER* optional, in/out -> "var" ; ParameterCount : DWORD -> "int" ; ※出力/バッファ引数は var 方式(変数を直接渡す)。varptr 方式にも切替可。; void* VirtualAlloc2(HANDLE Process, void* BaseAddress, UINT_PTR Size, VIRTUAL_ALLOCATION_TYPE AllocationType, DWORD PageProtection, MEM_EXTENDED_PARAMETER* ExtendedParameters, DWORD ParameterCount) #uselib "api-ms-win-core-memory-l1-1-6.dll" #cfunc global VirtualAlloc2 "VirtualAlloc2" intptr, intptr, intptr, int, int, intptr, int ; res = VirtualAlloc2(Process, BaseAddress, Size, AllocationType, PageProtection, varptr(ExtendedParameters), ParameterCount) ; Process : HANDLE optional -> "intptr" ; BaseAddress : void* optional -> "intptr" ; Size : UINT_PTR -> "intptr" ; AllocationType : VIRTUAL_ALLOCATION_TYPE -> "int" ; PageProtection : DWORD -> "int" ; ExtendedParameters : MEM_EXTENDED_PARAMETER* optional, in/out -> "intptr" ; ParameterCount : DWORD -> "int" ; ※出力/バッファ引数はポインタ方式(token=intptr / 呼び出しは varptr(変数))。
import (
"golang.org/x/sys/windows"
"unsafe"
)
var (
api_ms_win_core_memory_l1_1_6 = windows.NewLazySystemDLL("api-ms-win-core-memory-l1-1-6.dll")
procVirtualAlloc2 = api_ms_win_core_memory_l1_1_6.NewProc("VirtualAlloc2")
)
// Process (HANDLE optional), BaseAddress (void* optional), Size (UINT_PTR), AllocationType (VIRTUAL_ALLOCATION_TYPE), PageProtection (DWORD), ExtendedParameters (MEM_EXTENDED_PARAMETER* optional, in/out), ParameterCount (DWORD)
r1, _, err := procVirtualAlloc2.Call(
uintptr(Process),
uintptr(BaseAddress),
uintptr(Size),
uintptr(AllocationType),
uintptr(PageProtection),
uintptr(ExtendedParameters),
uintptr(ParameterCount),
)
_ = err // syscall.Errno (valid when the call sets last-error)
_ = r1 // void*function VirtualAlloc2(
Process: THandle; // HANDLE optional
BaseAddress: Pointer; // void* optional
Size: NativeUInt; // UINT_PTR
AllocationType: DWORD; // VIRTUAL_ALLOCATION_TYPE
PageProtection: DWORD; // DWORD
ExtendedParameters: Pointer; // MEM_EXTENDED_PARAMETER* optional, in/out
ParameterCount: DWORD // DWORD
): Pointer; stdcall;
external 'api-ms-win-core-memory-l1-1-6.dll' name 'VirtualAlloc2';result := DllCall("api-ms-win-core-memory-l1-1-6\VirtualAlloc2"
, "Ptr", Process ; HANDLE optional
, "Ptr", BaseAddress ; void* optional
, "UPtr", Size ; UINT_PTR
, "UInt", AllocationType ; VIRTUAL_ALLOCATION_TYPE
, "UInt", PageProtection ; DWORD
, "Ptr", ExtendedParameters ; MEM_EXTENDED_PARAMETER* optional, in/out
, "UInt", ParameterCount ; DWORD
, "Ptr") ; return: void*●VirtualAlloc2(Process, BaseAddress, Size, AllocationType, PageProtection, ExtendedParameters, ParameterCount) = DLL("api-ms-win-core-memory-l1-1-6.dll", "void* VirtualAlloc2(void*, void*, int, dword, dword, void*, dword)")
# 呼び出し: VirtualAlloc2(Process, BaseAddress, Size, AllocationType, PageProtection, ExtendedParameters, ParameterCount)
# Process : HANDLE optional -> "void*"
# BaseAddress : void* optional -> "void*"
# Size : UINT_PTR -> "int"
# AllocationType : VIRTUAL_ALLOCATION_TYPE -> "dword"
# PageProtection : DWORD -> "dword"
# ExtendedParameters : MEM_EXTENDED_PARAMETER* optional, in/out -> "void*"
# ParameterCount : DWORD -> "dword"
# なでしこ1は32bit・ANSI(Shift_JIS)。文字列=char*(ANSI)、ポインタ/ハンドル=void*(4byte)。const std = @import("std");
extern "api-ms-win-core-memory-l1-1-6" fn VirtualAlloc2(
Process: ?*anyopaque, // HANDLE optional
BaseAddress: ?*anyopaque, // void* optional
Size: usize, // UINT_PTR
AllocationType: u32, // VIRTUAL_ALLOCATION_TYPE
PageProtection: u32, // DWORD
ExtendedParameters: [*c]MEM_EXTENDED_PARAMETER, // MEM_EXTENDED_PARAMETER* optional, in/out
ParameterCount: u32 // DWORD
) callconv(std.os.windows.WINAPI) ?*anyopaque;proc VirtualAlloc2(
Process: pointer, # HANDLE optional
BaseAddress: pointer, # void* optional
Size: uint, # UINT_PTR
AllocationType: uint32, # VIRTUAL_ALLOCATION_TYPE
PageProtection: uint32, # DWORD
ExtendedParameters: ptr MEM_EXTENDED_PARAMETER, # MEM_EXTENDED_PARAMETER* optional, in/out
ParameterCount: uint32 # DWORD
): pointer {.importc: "VirtualAlloc2", stdcall, dynlib: "api-ms-win-core-memory-l1-1-6.dll".}pragma(lib, "api-ms-win-core-memory-l1-1-6");
extern(Windows)
void* VirtualAlloc2(
void* Process, // HANDLE optional
void* BaseAddress, // void* optional
size_t Size, // UINT_PTR
uint AllocationType, // VIRTUAL_ALLOCATION_TYPE
uint PageProtection, // DWORD
MEM_EXTENDED_PARAMETER* ExtendedParameters, // MEM_EXTENDED_PARAMETER* optional, in/out
uint ParameterCount // DWORD
);ccall((:VirtualAlloc2, "api-ms-win-core-memory-l1-1-6.dll"), stdcall, Ptr{Cvoid},
(Ptr{Cvoid}, Ptr{Cvoid}, Csize_t, UInt32, UInt32, Ptr{MEM_EXTENDED_PARAMETER}, UInt32),
Process, BaseAddress, Size, AllocationType, PageProtection, ExtendedParameters, ParameterCount)
# Process : HANDLE optional -> Ptr{Cvoid}
# BaseAddress : void* optional -> Ptr{Cvoid}
# Size : UINT_PTR -> Csize_t
# AllocationType : VIRTUAL_ALLOCATION_TYPE -> UInt32
# PageProtection : DWORD -> UInt32
# ExtendedParameters : MEM_EXTENDED_PARAMETER* optional, in/out -> Ptr{MEM_EXTENDED_PARAMETER}
# ParameterCount : DWORD -> UInt32
# stdcall は 32bit のみ意味を持つ(x64 では無視)。local ffi = require("ffi")
ffi.cdef[[
void* VirtualAlloc2(
void* Process,
void* BaseAddress,
uintptr_t Size,
uint32_t AllocationType,
uint32_t PageProtection,
void* ExtendedParameters,
uint32_t ParameterCount);
]]
local api-ms-win-core-memory-l1-1-6 = ffi.load("api-ms-win-core-memory-l1-1-6")
-- api-ms-win-core-memory-l1-1-6.VirtualAlloc2(Process, BaseAddress, Size, AllocationType, PageProtection, ExtendedParameters, ParameterCount)
-- Process : HANDLE optional
-- BaseAddress : void* optional
-- Size : UINT_PTR
-- AllocationType : VIRTUAL_ALLOCATION_TYPE
-- PageProtection : DWORD
-- ExtendedParameters : MEM_EXTENDED_PARAMETER* optional, in/out
-- ParameterCount : DWORD
-- 構造体/GUIDへのポインタは cdef が通るよう void* で表記(実型は各引数コメント参照)。値渡し構造体・enum は対応する typedef を cdef に追加すること。const koffi = require('koffi');
const lib = koffi.load('api-ms-win-core-memory-l1-1-6.dll');
const VirtualAlloc2 = lib.func('__stdcall', 'VirtualAlloc2', 'void *', ['void *', 'void *', 'uintptr_t', 'uint32_t', 'uint32_t', 'void *', 'uint32_t']);
// VirtualAlloc2(Process, BaseAddress, Size, AllocationType, PageProtection, ExtendedParameters, ParameterCount)
// Process : HANDLE optional -> 'void *'
// BaseAddress : void* optional -> 'void *'
// Size : UINT_PTR -> 'uintptr_t'
// AllocationType : VIRTUAL_ALLOCATION_TYPE -> 'uint32_t'
// PageProtection : DWORD -> 'uint32_t'
// ExtendedParameters : MEM_EXTENDED_PARAMETER* optional, in/out -> 'void *'
// ParameterCount : DWORD -> 'uint32_t'
// 出力ポインタは koffi.out(...) で包む。構造体は koffi.struct で定義。const lib = Deno.dlopen("api-ms-win-core-memory-l1-1-6.dll", {
VirtualAlloc2: { parameters: ["pointer", "pointer", "usize", "u32", "u32", "pointer", "u32"], result: "pointer" },
});
// lib.symbols.VirtualAlloc2(Process, BaseAddress, Size, AllocationType, PageProtection, ExtendedParameters, ParameterCount)
// Process : HANDLE optional -> "pointer"
// BaseAddress : void* optional -> "pointer"
// Size : UINT_PTR -> "usize"
// AllocationType : VIRTUAL_ALLOCATION_TYPE -> "u32"
// PageProtection : DWORD -> "u32"
// ExtendedParameters : MEM_EXTENDED_PARAMETER* optional, in/out -> "pointer"
// ParameterCount : DWORD -> "u32"
// 文字列引数は "buffer"(NUL 終端のバイト列を Uint8Array で渡す)。
// 値渡し構造体は { struct: [ ...field types... ] } を使用。<?php
$ffi = FFI::cdef(<<<C
void* VirtualAlloc2(
void* Process,
void* BaseAddress,
size_t Size,
uint32_t AllocationType,
uint32_t PageProtection,
void* ExtendedParameters,
uint32_t ParameterCount);
C, "api-ms-win-core-memory-l1-1-6.dll");
// $ffi->VirtualAlloc2(Process, BaseAddress, Size, AllocationType, PageProtection, ExtendedParameters, ParameterCount);
// Process : HANDLE optional
// BaseAddress : void* optional
// Size : UINT_PTR
// AllocationType : VIRTUAL_ALLOCATION_TYPE
// PageProtection : DWORD
// ExtendedParameters : MEM_EXTENDED_PARAMETER* optional, in/out
// ParameterCount : 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 Api-ms-win-core-memory-l1-1-6 extends StdCallLibrary {
Api-ms-win-core-memory-l1-1-6 INSTANCE = Native.load("api-ms-win-core-memory-l1-1-6", Api-ms-win-core-memory-l1-1-6.class);
Pointer VirtualAlloc2(
Pointer Process, // HANDLE optional
Pointer BaseAddress, // void* optional
long Size, // UINT_PTR
int AllocationType, // VIRTUAL_ALLOCATION_TYPE
int PageProtection, // DWORD
Pointer ExtendedParameters, // MEM_EXTENDED_PARAMETER* optional, in/out
int ParameterCount // DWORD
);
}@[Link("api-ms-win-core-memory-l1-1-6")]
lib Libapi-ms-win-core-memory-l1-1-6
fun VirtualAlloc2 = VirtualAlloc2(
Process : Void*, # HANDLE optional
BaseAddress : Void*, # void* optional
Size : LibC::SizeT, # UINT_PTR
AllocationType : UInt32, # VIRTUAL_ALLOCATION_TYPE
PageProtection : UInt32, # DWORD
ExtendedParameters : MEM_EXTENDED_PARAMETER*, # MEM_EXTENDED_PARAMETER* optional, in/out
ParameterCount : UInt32 # DWORD
) : Void*
end
# 構造体/GUID/enum は lib 内に対応する型定義が必要。
# 呼出規約: x64 は規約統一のため OK。x86(32bit)は WINAPI=stdcall だが Crystal の fun に stdcall 付与構文がなく非対応。import 'dart:ffi';
import 'package:ffi/ffi.dart';
typedef VirtualAlloc2Native = Pointer<Void> Function(Pointer<Void>, Pointer<Void>, UintPtr, Uint32, Uint32, Pointer<Void>, Uint32);
typedef VirtualAlloc2Dart = Pointer<Void> Function(Pointer<Void>, Pointer<Void>, int, int, int, Pointer<Void>, int);
final VirtualAlloc2 = DynamicLibrary.open('api-ms-win-core-memory-l1-1-6.dll')
.lookupFunction<VirtualAlloc2Native, VirtualAlloc2Dart>('VirtualAlloc2');
// Process : HANDLE optional -> Pointer<Void>
// BaseAddress : void* optional -> Pointer<Void>
// Size : UINT_PTR -> UintPtr
// AllocationType : VIRTUAL_ALLOCATION_TYPE -> Uint32
// PageProtection : DWORD -> Uint32
// ExtendedParameters : MEM_EXTENDED_PARAMETER* optional, in/out -> Pointer<Void>
// ParameterCount : DWORD -> Uint32
// 文字列は package:ffi の "...".toNativeUtf16()/toNativeUtf8() で変換。{$mode objfpc}{$H+}
function VirtualAlloc2(
Process: THandle; // HANDLE optional
BaseAddress: Pointer; // void* optional
Size: NativeUInt; // UINT_PTR
AllocationType: DWORD; // VIRTUAL_ALLOCATION_TYPE
PageProtection: DWORD; // DWORD
ExtendedParameters: Pointer; // MEM_EXTENDED_PARAMETER* optional, in/out
ParameterCount: DWORD // DWORD
): Pointer; stdcall;
external 'api-ms-win-core-memory-l1-1-6.dll' name 'VirtualAlloc2';import Foreign
import Foreign.C.Types
import Foreign.C.String
foreign import stdcall safe "VirtualAlloc2"
c_VirtualAlloc2 :: Ptr () -> Ptr () -> CUIntPtr -> Word32 -> Word32 -> Ptr () -> Word32 -> IO (Ptr ())
-- Process : HANDLE optional -> Ptr ()
-- BaseAddress : void* optional -> Ptr ()
-- Size : UINT_PTR -> CUIntPtr
-- AllocationType : VIRTUAL_ALLOCATION_TYPE -> Word32
-- PageProtection : DWORD -> Word32
-- ExtendedParameters : MEM_EXTENDED_PARAMETER* optional, in/out -> Ptr ()
-- ParameterCount : DWORD -> Word32
-- 要 GHC(Windows)。stdcall は x64 では ccall として扱われる。ブロックする API は safe 呼び出し推奨。open Ctypes
open Foreign
let virtualalloc2 =
foreign "VirtualAlloc2"
((ptr void) @-> (ptr void) @-> size_t @-> uint32_t @-> uint32_t @-> (ptr void) @-> uint32_t @-> returning (ptr void))
(* Process : HANDLE optional -> (ptr void) *)
(* BaseAddress : void* optional -> (ptr void) *)
(* Size : UINT_PTR -> size_t *)
(* AllocationType : VIRTUAL_ALLOCATION_TYPE -> uint32_t *)
(* PageProtection : DWORD -> uint32_t *)
(* ExtendedParameters : MEM_EXTENDED_PARAMETER* optional, in/out -> (ptr void) *)
(* ParameterCount : DWORD -> uint32_t *)
(* foreign は cdecl 前提。x64 Windows では WINAPI と一致。構造体は ctypes structure を定義のこと。 *)(cffi:define-foreign-library api-ms-win-core-memory-l1-1-6 (t "api-ms-win-core-memory-l1-1-6.dll"))
(cffi:use-foreign-library api-ms-win-core-memory-l1-1-6)
(cffi:defcfun ("VirtualAlloc2" virtual-alloc2 :convention :stdcall) :pointer
(process :pointer) ; HANDLE optional
(base-address :pointer) ; void* optional
(size :uint64) ; UINT_PTR
(allocation-type :uint32) ; VIRTUAL_ALLOCATION_TYPE
(page-protection :uint32) ; DWORD
(extended-parameters :pointer) ; MEM_EXTENDED_PARAMETER* optional, in/out
(parameter-count :uint32)) ; DWORD
; isize/usize(INT_PTR/SIZE_T)は x64 前提で :int64/:uint64。x86 では :int32/:uint32。use Win32::API;
my $VirtualAlloc2 = Win32::API::More->new('api-ms-win-core-memory-l1-1-6',
'LPVOID VirtualAlloc2(HANDLE Process, LPVOID BaseAddress, WPARAM Size, DWORD AllocationType, DWORD PageProtection, LPVOID ExtendedParameters, DWORD ParameterCount)');
# my $ret = $VirtualAlloc2->Call($Process, $BaseAddress, $Size, $AllocationType, $PageProtection, $ExtendedParameters, $ParameterCount);
# Process : HANDLE optional -> HANDLE
# BaseAddress : void* optional -> LPVOID
# Size : UINT_PTR -> WPARAM
# AllocationType : VIRTUAL_ALLOCATION_TYPE -> DWORD
# PageProtection : DWORD -> DWORD
# ExtendedParameters : MEM_EXTENDED_PARAMETER* optional, in/out -> LPVOID
# ParameterCount : DWORD -> DWORD
# 値渡し構造体は pack() した文字列、または Win32::API::Struct を使用。関連項目
- f VirtualAlloc — プロセスの仮想アドレス空間にメモリを確保する。
- f VirtualAllocEx — 指定プロセスの仮想アドレス空間にメモリ領域を予約またはコミットする。