如何在c#中通过lpEnvironment调用CreateProcess()

How to call CreateProcess() in C# passing lpEnvironment

本文关键字:调用 lpEnvironment CreateProcess      更新时间:2023-10-16

我将本地CreateProcess导入到我的c#项目中用于ICorDebug http://msdn.microsoft.com/en-us/library/vstudio/ms232508(v=vs.100).aspx

 [MethodImpl(MethodImplOptions.InternalCall, MethodCodeType = MethodCodeType.Runtime)]
        void CreateProcess([In, MarshalAs(UnmanagedType.LPWStr)] string lpApplicationName, [In, MarshalAs(UnmanagedType.LPWStr)] string lpCommandLine, [In] SECURITY_ATTRIBUTES lpProcessAttributes, [In] SECURITY_ATTRIBUTES lpThreadAttributes, [In] int bInheritHandles, [In] uint dwCreationFlags, [In] IntPtr lpEnvironment, [In, MarshalAs(UnmanagedType.LPWStr)] string lpCurrentDirectory, [In] STARTUPINFO pStartupInfo, [In] PROCESS_INFORMATION pProcessInformation, [In] CorDebugCreateProcessFlags debuggingFlags, [MarshalAs(UnmanagedType.Interface)] out ICorDebugProcess ppProcess);

我把它叫做试图这样传递lpEnvironment

            IntPtr intPtrEnv;
            if (variables != string.Empty)
                intPtrEnv = Marshal.StringToHGlobalUni(variables);
            else
                intPtrEnv = new IntPtr(0);
 p_codebugger.CreateProcess(
                                exepath,
                                exepath,
                                null,
                                null,
                                1, // inherit handles
                                (UInt32)CreateProcessFlags.CREATE_NEW_CONSOLE,
                                intPtrEnv,
                                ".",
                                si,
                                pi,
                                CorDebugCreateProcessFlags.DEBUG_NO_SPECIAL_OPTIONS,
                                out proc);

变量字符串包含:

"COR_ENABLE_PROFILING=1COR_PROFILER=PROFILER_GUIDCOR_PROFILER_PATH=GetProfilerFullPat"

我得到一个错误值超出允许范围

任何建议如何通过环境块从c#到c++ dll?

好的,我设法解决了我的问题。首先,我使用StringBuilder而不是IntPtr。添加字符串"COR_ENABLE_PROFILING=1COR_PROFILER=PROFILER_GUIDCOR_PROFILER_PATH=GetProfilerFullPat"我只是添加("COR_ENABLE_PROFILING=1")并增加Stringbuilder的长度+ 1等…;结束应该再增加一次,长度为++(这是ANSI编码);第二件事是更改并将封送添加到导入的方法中代替[In] IntPtr lpEnvironment添加[In, MarshalAs(UnmanagedType.LPStr)] StringBuilder lpEnvironment

没有必要为此使用p/Invoke,您可以使用。net Process。

如果你想自定义进程启动,传递环境变量等,使用一个接受ProcessStartInfo对象的重载。