gpt4 book ai didi

java - C++ 代码工作正常但在从 Java (JNI) 调用时不起作用

转载 作者:太空宇宙 更新时间:2023-11-04 14:18:31 25 4
gpt4 key购买 nike

我曾经在调用 ExitWindowsEX Windows API 函数时遇到一些权限问题。

所以我写了下面的代码来获取权限:

这在 C++ 中运行良好

#include <cstdlib>
#include <windows.h>
#include <iostream>


using namespace std;

/*
*
*/

int MyExitWindows(int flag, int reason);

int main(int argc, char** argv) {
MyExitWindows(EWX_SHUTDOWN, 0);
}

int MyExitWindows(int flag, int reason) {
HANDLE hToken;
TOKEN_PRIVILEGES tkp;

// Get a token for this process.

if (!OpenProcessToken(GetCurrentProcess(), TOKEN_ADJUST_PRIVILEGES | TOKEN_QUERY, &hToken))
return GetLastError();

// Get the LUID for the shutdown privilege.

LookupPrivilegeValue(NULL, SE_SHUTDOWN_NAME, &tkp.Privileges[0].Luid);

tkp.PrivilegeCount = 1; // one privilege to set
tkp.Privileges[0].Attributes = SE_PRIVILEGE_ENABLED;

// Get the shutdown privilege for this process.

AdjustTokenPrivileges(hToken, FALSE, &tkp, 0,
(PTOKEN_PRIVILEGES) NULL, 0);

// Cannot test the return value of AdjustTokenPrivileges.

ExitWindowsEx(flag, reason);
if (GetLastError() != ERROR_SUCCESS) {
return GetLastError();
}

return 0;
}

但是当我从 Java 调用它时这不起作用

#include <jni.h>
#include <cstdlib>
#include <windows.h>
#include "com_ehsunbehravesh_jshutdown_system_Shutdowner.h"

using namespace std;

int MyExitWindows(int flag, int reason);

JNIEXPORT jint JNICALL Java_com_ehsunbehravesh_jshutdown_system_Shutdowner_exitWindowsEx
(JNIEnv *env, jobject obj, jlong flag, jlong reason) {
return MyExitWindows(flag, reason);
}

int MyExitWindows(int flag, int reason) {
HANDLE hToken;
TOKEN_PRIVILEGES tkp;

// Get a token for this process.

int cpid = GetCurrentProcessId();
printf("%d", cpid);
if (!OpenProcessToken(GetCurrentProcess(), TOKEN_ADJUST_PRIVILEGES | TOKEN_QUERY, &hToken))
return GetLastError();

// Get the LUID for the shutdown privilege.

LookupPrivilegeValue(NULL, SE_SHUTDOWN_NAME, &tkp.Privileges[0].Luid);

tkp.PrivilegeCount = 1; // one privilege to set
tkp.Privileges[0].Attributes = SE_PRIVILEGE_ENABLED;

// Get the shutdown privilege for this process.

AdjustTokenPrivileges(hToken, FALSE, &tkp, 0,
(PTOKEN_PRIVILEGES) NULL, 0);

// Cannot test the return value of AdjustTokenPrivileges.

ExitWindowsEx(flag, reason);
if (GetLastError() != ERROR_SUCCESS) {
return GetLastError();
}

return 0;
}

最佳答案

您是否有任何理由不使用 System.exit(int)

Java 试图控制应用程序的关闭,也许它试图阻止您以其他方式关闭。

关于java - C++ 代码工作正常但在从 Java (JNI) 调用时不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9325964/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com