Running Python script from C++ code(.NET)
Gerard Flanagan
grflanagan at yahoo.co.uk
Wed Sep 27 04:29:40 EDT 2006
volcano wrote:
> volcano wrote:
> > Hello, folks!
> > A trivial question - I have a working Python script that I have to
> > invoke from C++ code. No fancy stuff - just run the whole script with
> > its parameters. No callbacks, no signalling - nada, just
> > stupid,primitive, straightforward call.
> >
> > And while there is a lot of help on embedding, I could not find out how
> > to run script as a whole.SOS!!!!
>
> Thanks a lot to all of you who cared to answer! Eventually it was
> "::CreateProcess", and it works!
>
I used to find http://pinvoke.net a good resource when I was doing
Active Directory stuff. Just for interest's sake, cutting and pasting
from the CreateProcess page, the following arcana will start Python (
again from C#, but here you can see the internals at least):
using System;
using System.Runtime.InteropServices;
class Class1
{
[StructLayout(LayoutKind.Sequential, CharSet=CharSet.Unicode)]
public struct STARTUPINFO
{
Int32 cb;
string lpReserved;
string lpDesktop;
string lpTitle;
Int32 dwX;
Int32 dwY;
Int32 dwXSize;
Int32 dwYSize;
Int32 dwXCountChars;
Int32 dwYCountChars;
Int32 dwFillAttribute;
Int32 dwFlags;
Int16 wShowWindow;
Int16 cbReserved2;
IntPtr lpReserved2;
IntPtr hStdInput;
IntPtr hStdOutput;
IntPtr hStdError;
}
[StructLayout(LayoutKind.Sequential)]
public struct PROCESS_INFORMATION
{
public IntPtr hProcess;
IntPtr hThread;
public int dwProcessId;
public int dwThreadId;
}
[StructLayout(LayoutKind.Sequential)]
public struct SECURITY_ATTRIBUTES
{
public int nLength;
public IntPtr lpSecurityDescriptor;
public int bInheritHandle;
}
[DllImport("kernel32.dll")]
public static extern bool CreateProcess(string lpApplicationName,
string lpCommandLine, ref SECURITY_ATTRIBUTES lpProcessAttributes,
ref SECURITY_ATTRIBUTES lpThreadAttributes, bool bInheritHandles,
uint dwCreationFlags, IntPtr lpEnvironment, string
lpCurrentDirectory,
ref STARTUPINFO lpStartupInfo,
out PROCESS_INFORMATION lpProcessInformation);
[STAThread]
static void Main(string[] args)
{
const uint NORMAL_PRIORITY_CLASS = 0x0020;
bool retValue;
string Application = @"c:\python\python24\python.exe";
string CommandLine = "";
PROCESS_INFORMATION pInfo = new PROCESS_INFORMATION();
STARTUPINFO sInfo = new STARTUPINFO();
SECURITY_ATTRIBUTES pSec = new SECURITY_ATTRIBUTES();
SECURITY_ATTRIBUTES tSec = new SECURITY_ATTRIBUTES();
pSec.nLength = Marshal.SizeOf(pSec);
tSec.nLength = Marshal.SizeOf(tSec);
retValue = CreateProcess(Application,CommandLine,
ref pSec,ref tSec,false,NORMAL_PRIORITY_CLASS,
IntPtr.Zero,null,ref sInfo,out pInfo);
}
}
More information about the Python-list
mailing list