Вот способ генерировать аргументы динамически. Это написано для Windows msvcrt
, но должно работать и для libc
:
test.cpp
#include <stdio.h>
#include <stdlib.h>
int main(int argc, char* argv[])
{
for(int i = 0; i < argc; ++i)
printf("argv[%d] = \"%s\"\n",i,argv[i]);
printf("TEST1=%s\n",getenv("TEST1"));
printf("TEST2=%s\n",getenv("TEST2"));
return 0;
}
test.py
from ctypes import *
dll = CDLL('msvcrt')
dll._execve.argtypes = c_char_p,POINTER(c_char_p),POINTER(c_char_p)
dll._execve.restype = c_ssize_t
cmd = b'test.exe'
args = [b'arg1',b'arg2',b'arg3']
env = [b'TEST1=hello',b'TEST2=goodbye']
# Convert Python lists to c_char_p arrays.
# Arrays should be null-terminated so adds None to the end.
cargs = (c_char_p * (len(args) + 2))(cmd,*args,None)
cenv = (c_char_p * (len(env) + 1))(*env,None)
dll._execve(cmd,cargs,cenv)
Выход:
argv[0] = "test.exe"
argv[1] = "arg1"
argv[2] = "arg2"
argv[3] = "arg3"
TEST1=hello
TEST2=goodbye