メソッドの本体を交換します。
Public Shared Sub SwapMethodBody( _
ByVal cls As Type, _ ByVal methodtoken As Integer, _ ByVal rgIL As IntPtr, _ ByVal methodSize As Integer, _ ByVal flags As Integer _)
[C#]
public static void SwapMethodBody(Typecls,intmethodtoken,IntPtrrgIL,intmethodSize,intflags);
[C++]
public: static void SwapMethodBody(Type* cls,intmethodtoken,IntPtrrgIL,intmethodSize,intflags);
[JScript]
public static function SwapMethodBody(
cls : Type,methodtoken : int,rgIL : IntPtr,methodSize : int,flags : int);
パラメータ
- cls
メソッドを格納しているクラス。 - methodtoken
メソッドのトークン。 - rgIL
メソッドを指すポインタ。これにはメソッド ヘッダーが含まれます。 - methodSize
新しいメソッド本体のサイズ (バイト単位)。 - flags
交換を制御するフラグ。定数の定義を参照してください。
例外
例外の種類 | 条件 |
---|---|
ArgumentNullException | cls が null 参照 (Visual Basic では Nothing) です。 |
NotSupportedException | 型 cls が不完全です。 |
解説
グローバル メソッドの本体を交換するこのメソッドを使用できません。
メソッド本体を交換する型を格納している動的モジュールを作成したクライアントだけが、このメソッドを呼び出すことができます。
使用例
[Visual Basic, C#, C++] メソッドの本体を新しい本体と交換する方法を次の例に示します。既存のメソッドのメソッド トークンを取得し、 SwapMethodBody に渡される MSIL (Microsoft Intermediate Language) を表すバイトの BLOB を構築する方法も示します。
Imports System
Imports System.Reflection
Imports System.Reflection.Emit
Imports System.Runtime.InteropServices
Class SwapMethodBodySample
' First make a method that returns 0.
' Then swap the method body with a body that returns 1.
Public Shared Sub Main()
' Construct a dynamic assembly
Dim g As Guid = Guid.NewGuid()
Dim asmname As New AssemblyName()
asmname.Name = "tempfile" + g.ToString()
Dim asmbuild As AssemblyBuilder = _
System.Threading.Thread.GetDomain().DefineDynamicAssembly _
(asmname, AssemblyBuilderAccess.Run)
' Add a dynamic module that contains one type that has one method that
' has no arguments.
Dim modbuild As ModuleBuilder = asmbuild.DefineDynamicModule("test")
Dim tb As TypeBuilder = modbuild.DefineType("name of the Type")
Dim somemethod As MethodBuilder = _
tb.DefineMethod("My method Name", _
MethodAttributes.Public Or(MethodAttributes.Static), _
GetType(Integer), New Type() {})
' Define the body of the method to return 0.
Dim ilg As ILGenerator = somemethod.GetILGenerator()
ilg.Emit(OpCodes.Ldc_I4_0)
ilg.Emit(OpCodes.Ret)
' Complete the type and verify that it returns 0.
Dim tbBaked As Type = tb.CreateType()
Dim res1 As Integer = _
CInt(tbBaked.GetMethod("My method Name").Invoke _
(Nothing, New Object() {}))
If res1 <> 0 Then
Console.WriteLine("Err_001a, should have returned 0")
Else
Console.WriteLine("Original method returned 0")
End If
' Define a new method body that will return a 1 instead.
Dim methodBytes As Byte() = _
{&H3, &H30, &HA, &H0, &H2, &H0, &H0, &H0, &H0, &H0, &H0, &H0, &H17, &H2A}
'&H2 code size
'&H17 ldc_i4_1
'&H2A ret
' Get the token for the method whose body you are replacing.
Dim somemethodToken As MethodToken = somemethod.GetToken()
' Get the pointer to the method body.
Dim hmem As GCHandle = _
GCHandle.Alloc(CType(methodBytes, Object), GCHandleType.Pinned)
Dim addr As IntPtr = hmem.AddrOfPinnedObject()
Dim cbSize As Integer = methodBytes.Length
' Swap the old method body with the new body.
MethodRental.SwapMethodBody(tbBaked, somemethodToken.Token, addr, _
cbSize, MethodRental.JitImmediate)
' Verify that the modified method returns 1.
Dim res2 As Integer = _
CInt(tbBaked.GetMethod("My method Name").Invoke _
(Nothing, New Object() {}))
If res2 <> 1 Then
Console.WriteLine("Err_001b, should have returned 1")
Else
Console.WriteLine("Swapped method body returned 1")
End If
End Sub
End Class
[C#]
using System;
using System.Reflection;
using System.Reflection.Emit;
using System.Runtime.InteropServices;
class SwapMethodBodySample
{
// First make a method that returns 0.
// Then swap the method body with a body that returns 1.
public static void Main(String [] args)
{
// Construct a dynamic assembly
Guid g = Guid.NewGuid();
AssemblyName asmname = new AssemblyName();
asmname.Name = "tempfile" + g;
AssemblyBuilder asmbuild = System.Threading.Thread.GetDomain().
DefineDynamicAssembly(asmname, AssemblyBuilderAccess.Run);
// Add a dynamic module that contains one type that has one method that
// has no arguments.
ModuleBuilder modbuild = asmbuild.DefineDynamicModule( "test");
TypeBuilder tb = modbuild.DefineType( "name of the Type" );
MethodBuilder somemethod = tb.DefineMethod
("My method Name",
MethodAttributes.Public | MethodAttributes.Static,
typeof(int),
new Type[]{} );
// Define the body of the method to return 0.
ILGenerator ilg = somemethod.GetILGenerator();
ilg.Emit(OpCodes.Ldc_I4_0);
ilg.Emit(OpCodes.Ret);
// Complete the type and verify that it returns 0.
Type tbBaked = tb.CreateType();
int res1 = (int)tbBaked.GetMethod("My method Name").Invoke( null, new Object[]{} );
if ( res1 != 0 ) {
Console.WriteLine( "Err_001a, should have returned 0" );
} else {
Console.WriteLine("Original method returned 0");
}
// Define a new method body that will return a 1 instead.
Byte[] methodBytes = {
0x03,
0x30,
0x0A,
0x00,
0x02, // code size
0x00,
0x00,
0x00,
0x00,
0x00,
0x00,
0x00,
0x17, // ldc_i4_1
0x2a // ret
};
// Get the token for the method whose body you are replacing.
MethodToken somemethodToken = somemethod.GetToken();
// Get the pointer to the method body.
GCHandle hmem = GCHandle.Alloc((Object) methodBytes, GCHandleType.Pinned);
IntPtr addr = hmem.AddrOfPinnedObject();
int cbSize = methodBytes.Length;
// Swap the old method body with the new body.
MethodRental.SwapMethodBody(
tbBaked,
somemethodToken.Token,
addr,
cbSize,
MethodRental.JitImmediate);
// Verify that the modified method returns 1.
int res2 = (int)tbBaked.GetMethod("My method Name").Invoke( null, new Object[]{} );
if ( res2 != 1 ) {
Console.WriteLine( "Err_001b, should have returned 1" );
} else {
Console.WriteLine("Swapped method body returned 1");
}
}
}
[C++]
#using <mscorlib.dll>
using namespace System;
using namespace System::Reflection;
using namespace System::Reflection::Emit;
using namespace System::Runtime::InteropServices;
// First make a method that returns 0.
// Then swap the method body with a body that returns 1.
int main()
{
// Construct a dynamic assembly
Guid g = Guid::NewGuid();
AssemblyName* asmname = new AssemblyName();
asmname->Name = String::Concat( S"tempfile", __box(g));
AssemblyBuilder* asmbuild =
System::Threading::Thread::GetDomain()->DefineDynamicAssembly(asmname, AssemblyBuilderAccess::Run);
// Add a dynamic module that contains one type that has one method that
// has no arguments.
ModuleBuilder* modbuild = asmbuild->DefineDynamicModule( S"test");
TypeBuilder* tb = modbuild->DefineType( S"name of the Type" );
Type* temp2 [];
MethodBuilder* somemethod = tb->DefineMethod(S"My method Name",
static_cast<MethodAttributes>(MethodAttributes::Public | MethodAttributes::Static),
__typeof(int),
temp2 );
// Define the body of the method to return 0.
ILGenerator* ilg = somemethod->GetILGenerator();
ilg->Emit(OpCodes::Ldc_I4_0);
ilg->Emit(OpCodes::Ret);
// Complete the type and verify that it returns 0.
Type* tbBaked = tb->CreateType();
Object* temp0 [];
int res1 = *dynamic_cast<Int32*>(tbBaked->GetMethod(S"My method Name")->Invoke( 0, temp0 ));
if ( res1 != 0 ) {
Console::WriteLine( S"Err_001a, should have returned 0" );
} else {
Console::WriteLine(S"Original method returned 0");
}
// Define a new method body that will return a 1 instead.
Byte methodBytes[] = {
0x03,
0x30,
0x0A,
0x00,
0x02, // code size
0x00,
0x00,
0x00,
0x00,
0x00,
0x00,
0x00,
0x17, // ldc_i4_1
0x2a // ret
};
// Get the token for the method whose body you are replacing.
MethodToken somemethodToken = somemethod->GetToken();
// Get the pointer to the method body.
GCHandle hmem = GCHandle::Alloc((Object*) methodBytes, GCHandleType::Pinned);
IntPtr addr = hmem.AddrOfPinnedObject();
int cbSize = methodBytes->Length;
// Swap the old method body with the new body.
MethodRental::SwapMethodBody(
tbBaked,
somemethodToken.Token,
addr,
cbSize,
MethodRental::JitImmediate);
// Verify that the modified method returns 1.
Object* temp1 [];
int res2 = *dynamic_cast<Int32*>(tbBaked->GetMethod(S"My method Name")->Invoke( 0, temp1 ));
if ( res2 != 1 ) {
Console::WriteLine( S"Err_001b, should have returned 1" );
} else {
Console::WriteLine(S"Swapped method body returned 1");
}
}
[JScript] JScript のサンプルはありません。Visual Basic、C#、および C++ のサンプルを表示するには、このページの左上隅にある言語のフィルタ ボタン をクリックします。
必要条件
プラットフォーム: Windows 98, Windows NT 4.0, Windows Millennium Edition, Windows 2000, Windows XP Home Edition, Windows XP Professional, Windows Server 2003 ファミリ
.NET Framework セキュリティ:
- ReflectionPermission (Type.InvokeMember などの機構を通じて遅延バインディングで呼び出すときに必要なアクセス許可) ReflectionPermissionFlag.MemberAccess (関連する列挙体)
参照
MethodRental クラス | MethodRental メンバ | System.Reflection.Emit 名前空間