从c++中为Batch设置临时环境变量

Setting a temporary environment variable for Batch from C++

本文关键字:环境变量 设置 Batch c++ 中为      更新时间:2023-10-16

我正在实现一个小程序包,供批处理用户使用。这个包中几乎所有的东西都是用c++编写的,并从Java调用。

如何设置批处理文件使用的环境变量?

我试过使用这个:

JNIEXPORT void JNICALL METHOD_NAME(JNIEnv *env, jclass theclass, jstring key, jstring value) {
        const char* thekey = env->GetStringUTFChars(key, false);
        const char* thevalue = env->GetStringUTFChars(value, false);
        std::string envvar;
        envvar.append(thekey);
        envvar.append("=");
        envvar.append(thevalue);
        _putenv(envvar.c_str());
        env->ReleaseStringUTFChars(key, thekey);
        env->ReleaseStringUTFChars(value, thevalue);
}

但是批处理文件没有看到任何新的变量。我应该使用system("set thing=value");吗?

经过一番研究,我得出结论,子进程不能修改父进程的环境。