unit dynload;
interface
uses System.Reflection, System.Reflection.Emit, System.Threading, System.Runtime.InteropServices;
function CreateDelegate(ptr: Integer; dtype: System.
Type): Delegate;
function LoadLibrary(filename:
string): Integer;
external '
Kernel32.dll';
procedure FreeLibrary(
handle: Integer);
external '
Kernel32.dll';
function GetProcAddress(
handle: Integer;
name:
string): Integer;
implementation
var
modbuilder: ModuleBuilder;
asmbuilder: AssemblyBuilder;
[DllImport('
Kernel32.dll')]
function GetProcAddress(
handle:Integer;
name:
string):Integer;
begin
end;
function CreateDelegate(ptr:Integer;dtype:System.
Type):Delegate;
var
d, m2: MethodInfo;
paramlist:
array of System.
Type;
i: Integer;
t: TypeBuilder;
t2: System.
Type;
m: MethodBuilder;
ilgen: ILGenerator;
begin
d := dtype.GetMethod('
Invoke');
setlength(paramlist, Length(d.GetParameters));
for i := 0
to Length(paramlist) - 1
do
paramlist[i] := d.GetParameters[i].ParameterType;
t := modbuilder.DefineType('
_' + dtype.
Name);
m := t.DefineMethod('
Invoke', MethodAttributes.
Static or MethodAttributes.
Public,d.ReturnType,paramlist);
ilgen := m.GetILGenerator;
for i := 0
to Length(paramlist) - 1
do
ilgen.Emit(OpCodes.Ldarg, i);
ilgen.Emit(OpCodes.Ldc_I4, Integer(ptr));
ilgen.EmitCalli(OpCodes.Calli, CallingConvention.
StdCall, d.ReturnType, paramlist);
ilgen.Emit(OpCodes.Ret);
t2 := t.CreateType();
m2 := t2.GetMethod('
Invoke');
Result := Delegate.CreateDelegate(dtype, m2);
end;
procedure InitAssembly;
var
name: AssemblyName;
begin
name := AssemblyName.Create;
name.
Name := '
Temp';
asmbuilder := Thread.GetDomain.DefineDynamicAssembly(
name, AssemblyBuilderAccess.Run);
modbuilder := asmbuilder.DefineDynamicModule('
Temp');
end;
initialization
InitAssembly;
end.