2009-05-20 69 views
0

爲了學習F#和.Net,我一直在玩即將發佈的DLR。爲了實現這個目標,我一直在反思,努力實現一個與clr很好地集成的基本類型系統。雖然我能夠實例化一個擴展Object的簡單類型,但在調用它定義的方法時出現錯誤。使用委託/ DLR Lambdas覆蓋實例方法?

因爲在一天結束時DLR LambdaExpressions會編譯到委託中,我所做的是將生成的MethodInfo從生成的委託中取出並調用它,並使用生成的方法的參數填充堆棧。然後返回它。這是我的錯誤。

這裏是我的代碼:

open System 
open System.Reflection 
open System.Reflection.Emit 

type ConstructorInformation= 
    {Types:System.Type array} 

type MethodInformation= 
    {ParamTypes:System.Type array; 
    Name:string 
    Impl:System.Delegate} 


let rec addConstructors (t:TypeBuilder) (baseType:System.Type) constructorInfos = 
    match constructorInfos with 
     |ci::rest -> 
      let cb = t.DefineConstructor(MethodAttributes.Public, CallingConventions.Standard,ci.Types) 
      let ilGen = cb.GetILGenerator() 

      ilGen.Emit(OpCodes.Ldarg_0) 
      Array.iteri (fun (index:int) _-> ilGen.Emit(OpCodes.Ldarg, index+1)) ci.Types 
      ilGen.Emit(OpCodes.Call, baseType.GetConstructor(ci.Types)) 
      addConstructors t baseType rest 
     |[] ->() 

let rec addMethods (tb:TypeBuilder) baseType methodInfos = 
    match methodInfos with 
    |mi::rest -> 
     let mb = tb.DefineMethod(mi.Name, MethodAttributes.Public, typeof<obj>, mi.ParamTypes) 
     let ilGen = mb.GetILGenerator() 
     ilGen.Emit(OpCodes.Ldarg_0) 
     Array.iteri (fun index _ -> ilGen.Emit(OpCodes.Ldarg, index+1)) mi.ParamTypes 
     ilGen.EmitCall(OpCodes.Call, mi.Impl.Method, mi.ParamTypes) 
     ilGen.Emit(OpCodes.Ret) 
     addMethods tb baseType rest 
    |[] ->() 

let defineType (baseType:System.Type) constructorInfos methodInfos= 
    let ab = AppDomain.CurrentDomain.DefineDynamicAssembly(AssemblyName("test"), AssemblyBuilderAccess.Run) 
    let mb = ab.DefineDynamicModule("test") 
    let typeBuilder = mb.DefineType("testType", TypeAttributes.Public, baseType)// | TypeAttributes.Class 
    addConstructors typeBuilder baseType constructorInfos 
    addMethods typeBuilder baseType methodInfos 
    typeBuilder.CreateType() 

type Delegate1 = delegate of obj -> obj 
let echo y:#obj= (y :> obj) 
let del1 : Delegate1 = new Delegate1(echo) 

let mis:MethodInformation list=[{Impl=del1; Name="Echo"; ParamTypes=[|(typeof<obj>)|]}] 
let cis:ConstructorInformation list=[] 
let t= defineType (typeof<obj>) cis mis 
let cinfo = t.GetConstructor([||]) 
let instance =cinfo.Invoke([||]) 
instance.GetType() 
(t.GetMethod("Echo")).Invoke(instance, [| (1:>obj)|]) 

這是我的錯誤,從FSI:

System.Reflection.TargetInvocationException: Exception has been thrown by the target of an invocation. ---> System.MethodAccessException: [email protected](System.Object) 
    at testType.Echo(Object) 
    --- End of inner exception stack trace --- 
    at System.RuntimeMethodHandle._InvokeMethodFast(Object target, Object[] arguments, SignatureStruct& sig, MethodAttributes methodAttributes, RuntimeTypeHandle typeOwner) 
    at System.RuntimeMethodHandle.InvokeMethodFast(Object target, Object[] arguments, Signature sig, MethodAttributes methodAttributes, RuntimeTypeHandle typeOwner) 
    at System.Reflection.RuntimeMethodInfo.Invoke(Object obj, BindingFlags invokeAttr, Binder binder, Object[] parameters, CultureInfo culture, Boolean skipVisibilityChecks) 
    at System.Reflection.RuntimeMethodInfo.Invoke(Object obj, BindingFlags invokeAttr, Binder binder, Object[] parameters, CultureInfo culture) 
    at <StartupCode$FSI_0002>.$FSI_0002._main() 
stopped due to error 

任何幫助或建議,將不勝感激 - 我有點淨福利局的,所以我的錯可能很簡單。

Mike Kohout

+0

在黑暗中拍攝 - 在使用fsc.exe編譯時是否獲得相同的行爲? MethodAccessException表明可能有些東西不是公開的,但你所有的代碼似乎都會產生公共方法,所以我不知道爲什麼會發生這種情況...... – Brian 2009-05-20 15:28:44

回答

0

嗯,我解決了它。生成的cil很糟糕。另外,我不得不對代表進行動態調用,而不是它所面對的功能。

#light 

open System 
open System.Reflection 
open System.Reflection.Emit 

type ConstructorInformation= 
    {Types:System.Type array} 

type MethodInformation= 
    {ParamTypes:System.Type array; 
    Name:string; 
    Impl:System.Delegate; 
    mutable Field:FieldBuilder option} 


let rec addConstructors (t:TypeBuilder) (baseType:System.Type) constructorInfos = 
    match constructorInfos with 
     |ci::rest -> 
      let cb = t.DefineConstructor(MethodAttributes.Public, CallingConventions.Standard,ci.Types) 
      let ilGen = cb.GetILGenerator() 

      ilGen.Emit(OpCodes.Ldarg_0) 
      Array.iteri (fun (index:int) _-> ilGen.Emit(OpCodes.Ldarg, index+1)) ci.Types 
      ilGen.Emit(OpCodes.Call, baseType.GetConstructor(ci.Types)) 
      addConstructors t baseType rest 
     |[] ->() 

let rec addMethods (tb:TypeBuilder) baseType methodInfos = 
    match methodInfos with 
    |mi::rest -> 
     let fb = tb.DefineField(mi.Name+"_field", typeof<Delegate>, FieldAttributes.Public); 
     mi.Field <- Some(fb) 
     let mb = tb.DefineMethod(mi.Name, MethodAttributes.Public, typeof<obj>, mi.ParamTypes) 
     let ilGen = mb.GetILGenerator() 
     let arrayLocal = ilGen.DeclareLocal((typeof<obj[]>)) 
     ilGen.Emit(OpCodes.Ldarg_0) 
     ilGen.Emit(OpCodes.Ldfld, fb) 
     ilGen.Emit(OpCodes.Ldc_I4, Array.length mi.ParamTypes) 
     ilGen.Emit(OpCodes.Newarr, typeof<obj>) 
     ilGen.Emit(OpCodes.Stloc, arrayLocal) 
     ilGen.Emit(OpCodes.Ldloc, arrayLocal) 
     Array.iteri (fun index _ -> ilGen.Emit(OpCodes.Ldc_I4, index) 
            ilGen.Emit(OpCodes.Ldarg, index+1) 
            ilGen.Emit(OpCodes.Stelem_Ref) 
            ilGen.Emit(OpCodes.Ldloc, arrayLocal)) mi.ParamTypes 
     ilGen.EmitCall(OpCodes.Callvirt, (mi.Impl.GetType()).GetMethod("DynamicInvoke", [|(typeof<obj[]>)|]), mi.ParamTypes) 
     ilGen.Emit(OpCodes.Ret) 
     addMethods tb baseType rest 
    |[] ->() 

let defineType (baseType:System.Type) constructorInfos methodInfos= 
    let ab = AppDomain.CurrentDomain.DefineDynamicAssembly(AssemblyName("test"), AssemblyBuilderAccess.Run) 
    let mb = ab.DefineDynamicModule("test") 
    let typeBuilder = mb.DefineType("testType", TypeAttributes.Public, baseType)// | TypeAttributes.Class 
    addConstructors typeBuilder baseType constructorInfos 
    addMethods typeBuilder baseType methodInfos 
    typeBuilder.CreateType() 

type Delegate1 = delegate of obj -> obj 
let echo y:#obj= (y :> obj) 
let del1 : Delegate1 = new Delegate1(echo) 

type Delegate2 = delegate of obj * obj -> obj 
let echoFirst (x:#obj) (y:#obj)=(x:>obj) 
let echoFirstDelegate:Delegate2 = new Delegate2(echoFirst) 
echoFirstDelegate.DynamicInvoke([|(1:>obj);(2:>obj)|]) 
//let mis:MethodInformation list=[{Impl=del1; Name="Echo"; ParamTypes=[|(typeof<obj>)|];Field=None}] 
//let cis:ConstructorInformation list=[] 
//let t= defineType (typeof<obj>) cis mis 
//let cinfo = t.GetConstructor([||]) 
//let instance =cinfo.Invoke([||]) 
//instance.GetType() 
//(t.GetField("Echo_field")).SetValue(instance, del1) 
//let fieldDelegate = (t.GetField("Echo_field")).GetValue(instance) :?> Delegate 
//(t.GetMethod("Echo")).Invoke(instance, [| (1:>obj)|]) 

//del1.DynamicInvoke([|(1:>obj)|]) 

let mis:MethodInformation list=[{Impl=del1; Name="Echo"; ParamTypes=[|(typeof<obj>)|];Field=None}; 
           {Impl=echoFirstDelegate; Name="EchoFirst"; ParamTypes=[| (typeof<obj>);(typeof<obj>)|]; Field=None}] 
let cis:ConstructorInformation list=[] 
let t= defineType (typeof<obj>) cis mis 
let cinfo = t.GetConstructor([||]) 
let instance =cinfo.Invoke([||]) 
instance.GetType() 
(t.GetField("Echo_field")).SetValue(instance, del1) 
let fieldDelegate = (t.GetField("Echo_field")).GetValue(instance) :?> Delegate 
(t.GetMethod("Echo")).Invoke(instance, [| (1:>obj)|]) 
(t.GetField("EchoFirst_field")).SetValue(instance, echoFirstDelegate) 
(t.GetMethod("EchoFirst")).Invoke(instance, [| (1:>obj);(2:>obj)|])