问题
I am calling Kernel32.Instance.CreateProcess
to start a detached process. One issue I am facing is attempting to pass a environment block to CreateProcess
each time I do the process does not start.
I first used
Advapi32Util.getEnvironmentBlock(environment)
to create the block, then to make a Pointer (needed by CreateProcess
( I used:
public static Pointer asPointer(String string) {
byte[] data;
try {
data = Native.toByteArray(string, "UTF-8");
} catch (UnsupportedEncodingException e) {
throw new RuntimeException(e);
}
Pointer pointer = new Memory(data.length + 1);
pointer.write(0, data, 0, data.length);
pointer.setByte(data.length, (byte) 0);
return pointer;
}
That I think results in the double null needed at the end. I did actually set CREATE_UNICODE_ENVIRONMENT so I tried add two extra nulls to the end of the Memory
. That still resulted in CreateProcess
returning false and not starting the command.
I don't understand what I am doing wrong. Should I be checking a log file that might hint at the problem?
回答1:
Ah So it seems while using CREATE_UNICODE_ENVIRONMENT
it needs to take UTF-16LE
byte[]
. Ensure that each key=value
is followed by two nulls aka (byte) 0)
. Finally add two more null bytes. The pointer can be made as above.
来源:https://stackoverflow.com/questions/50520947/how-to-pass-a-environment-pointer-to-windows-createprocess-in-java-using-jna