How to pass a Environment Pointer to Windows CreateProcess in Java (using jna)

醉酒当歌 提交于 2019-12-23 17:05:10

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!