【问题标题】:What is the C++ equivalent of .net's currentProcess.MainModule?.net 当前 Process.MainModule 的 C++ 等价物是什么?
【发布时间】:2012-03-21 16:45:10
【问题描述】:

在 c# 中这样做时

// get the current process
Process currentProcess  = System.Diagnostics.Process.GetCurrentProcess();

我可以的

currentProcess.MainModule

c++中有没有类似的函数?

【问题讨论】:

  • 你能提供更多关于你需要什么的信息吗?您想获取运行代码的位置,还是启动进程的主 .exe 的位置?

标签: c# c++ winapi process


【解决方案1】:

我假设您指的是 Windows。如果是这样,那么你需要这个:

GetModuleHandle(NULL);

这将返回用于创建进程的模块的模块句柄。在GetModuleHandle 的文档中找到完整的详细信息。

如果你想要模块的文件名,而不是模块句柄,那么你需要GetModuleFileName

【讨论】:

    【解决方案2】:

    ILSpy查看GetProcess()的反编译源代码:

    public static Process GetCurrentProcess()
    {
        return new Process(".", false, NativeMethods.GetCurrentProcessId(), null);
    }
    

    NativeMethods.GetCurrentProcessId() 被声明为

    [DllImport("kernel32.dll", CharSet = CharSet.Auto)]
    public static extern int GetCurrentProcessId();
    

    指的是GetCurrentProcessId function

    MainModule 定义为

    public ProcessModule MainModule
    {
        get
        {
            if (this.OperatingSystem.Platform == PlatformID.Win32NT)
            {
                this.EnsureState((Process.State)3);
                ModuleInfo firstModuleInfo = 
                    NtProcessManager.GetFirstModuleInfo(this.processId);
                return new ProcessModule(firstModuleInfo);
            }
            ProcessModuleCollection processModuleCollection = this.Modules;
            this.EnsureState(Process.State.HaveProcessInfo);
            foreach (ProcessModule processModule in processModuleCollection)
            {
                if (processModule.moduleInfo.Id == this.processInfo.mainModuleId)
                {
                    return processModule;
                }
            }
            return null;
        }
    }
    

    这似乎又回到了EnumProcessModules native function

    因此,通过同时使用GetCurrentProcessIdEnumProcessModules 函数,您应该能够获得与

    相似的结果
    currentProcess.MainModule
    

    【讨论】:

    • 我不明白。您将调用 EnumProcessModules 来枚举模块句柄,然后等到看到等于 GetModuleHandle(NULL) 的模块句柄,然后返回那个?!真的吗?
    • @DavidHeffernan 抱歉,我的回答太复杂了。回到 MFC 方式,我按照您描述的方式进行操作(带有一些 Afx 前缀,IIRC)。我刚刚概述了通过 .NET Framework 的(如您所说的不完整)路径,因为它似乎正在这样做。
    • .net 库正在维护模块句柄周围的包装类。即使存在单行版本,您的答案被接受也不是您的错!我只是想让提问者明白存在琐碎的解决方案。
    猜你喜欢
    • 1970-01-01
    • 2010-10-02
    • 1970-01-01
    • 2014-05-08
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多