Hey,

I think the issue comes from the fact that you're importing references to
the current runtime, which could be different from the one you're running
on.

Instead of doing Import (typeof (int)) you can use
assemblyDef.MainModule.TypeSystem.Int32.

I really recommend not using the Import overloads that take a
System.Reflection type and rather use the overloads that take a Cecil type,
this way you control exactly what ends up being referenced.

Jb



On Mon, Aug 8, 2016 at 7:28 AM, cheng yubao <[email protected]> wrote:

> Hi,
>
> I am using cecil library to inject some codes into main function. The
> injected codes will call a interface from Windows native DLL. Its interface
> is defined as" int fun1(int i) ".
>
>
> Please see the following sample code:
> ____________________________________________________________
> ____________________________________________________________
> ___________________
>
>
>   ModuleReference module_ref = new ModuleReference("test.dll");
>   assemblyDef.MainModule.ModuleReferences.Add(module_ref);
>
>   TypeReference nativeIntType = assemblyDef.main_module.
> Import(typeof(Int32));
>
>    //add import reference
>    MethodDefinition importMethod = new MethodDefinition("fun1",
>                 Mono.Cecil.MethodAttributes.HideBySig |
> Mono.Cecil.MethodAttributes.Private
>                 | Mono.Cecil.MethodAttributes.Static |
> Mono.Cecil.MethodAttributes.PInvokeImpl
>                 | Mono.Cecil.MethodAttributes.ReuseSlot, nativeIntType);
>     importMethod.ImplAttributes = Mono.Cecil.MethodImplAttributes.PreserveSig
> | Mono.Cecil.MethodImplAttributes.Managed | Mono.Cecil.
> MethodImplAttributes.IL;
>     importMethod.PInvokeInfo = new 
> PInvokeInfo(PInvokeAttributes.CallConvCdecl,
> "fun1", module_ref);
>     importMethod.Parameters.Add(new ParameterDefinition("i", 
> Mono.Cecil.ParameterAttributes.None,
> nativeIntType));
> ————————————————————————————————————————————————————————————
> ———————————————
>
> Above codes can work well for the application compiled by dot net 2.0, 30,
> 3,5, however it will throw System.InvalidProgramException for the
> application compiled by dot net 4.0.
>
> I must say that cecil is a wonderful library I ever used for dot net file
> handling. But this issue troubled me for several weeks. Hope anyone can
> help me to fix it?
>
>
>
> --
> --
> --
> mono-cecil
> ---
> You received this message because you are subscribed to the Google Groups
> "mono-cecil" group.
> To unsubscribe from this group and stop receiving emails from it, send an
> email to [email protected].
> For more options, visit https://groups.google.com/d/optout.
>

-- 
-- 
--
mono-cecil
--- 
You received this message because you are subscribed to the Google Groups 
"mono-cecil" group.
To unsubscribe from this group and stop receiving emails from it, send an email 
to [email protected].
For more options, visit https://groups.google.com/d/optout.

Reply via email to