Search code examples
cilmono.cecil

Mono.Cecil - How can I found out PInvoke DLL name?


Mono.Cecil provides a way to check whether a method is pinvoke or not with method.IsPInvokeImpl, and also provides more info with method.PInvokeInfo. How can I find out dll name ?


Solution

  • The IL for P/Invoke methods looks like this (for example, kernel32!LockFile):

    .method assembly hidebysig static pinvokeimpl("kernel32.dll" lasterr winapi) 
        bool LockFile (
            class Microsoft.Win32.SafeHandles.SafeFileHandle handle,
            int32 offsetLow,
            int32 offsetHigh,
            int32 countLow,
            int32 countHigh
        ) cil managed preservesig 
    {
    }
    

    Mono.Cecil mirrors the pinvokeimpl metadata in the PInvokeInfo class, with the first string packaged up as a ModuleReference. Hence, method.PInvokeInfo.Module.Name gives the DLL/dylib name.