如何将 Java 程序的入口点更改为 C 签名

How to change entry point of a Java program to a C signature?

本文关键字:签名 入口 Java 程序      更新时间:2023-10-16

我在玩弄JNA,试图在Java程序中执行一些C代码。这是我在网上找到的一个工作示例(构建路径中需要 JNA):

package core;
import com.sun.jna.Library;
import com.sun.jna.Native;
import com.sun.jna.Platform;
public class CoreController {
    public interface CLibrary extends Library {
        CLibrary INSTANCE = (CLibrary) Native.loadLibrary(
                (Platform.isWindows() ? "msvcrt" : "c"), CLibrary.class);
        void printf(String format, Object... args);
    }
    public static void main(String[] args) {
        CLibrary.INSTANCE.printf("Hello, Worldn");
        for (int i = 0; i < args.length; i++) {
            CLibrary.INSTANCE.printf("Argument %d: %sn", i, args[i]);
        }
        Native.main(args);
    }
}

实际上,我正在尝试做三件(看似无情的)事情。

1.) 程序的入口点应更改为以下 C 签名:

void __stdcall RVExtension(char *output, int outputSize, const char *function);

2.) Java 程序应该能够设置给定的output参数。
3.) 程序应编译为 DLL。

在C++中,此问题将按如下方式解决:

#include "stdafx.h"
extern "C" {
    __declspec (dllexport) void __stdcall RVExtension(char *output, int outputSize, const char *function);
}
void __stdcall RVExtension(char *output, int outputSize, const char *function) {
    strncpy_s(output, outputSize, "IT WORKS!", _TRUNCATE);
}

所以问题是,Java在某种程度上可能吗?如果是这样,我很高兴看到一些代码示例,因为我在这里进入了很多新领域。我什至不知道JNA在这里是否是一个合适的解决方案。如果有人有其他想法,请告诉!

亲切问候
杰森

您必须编写一个常规的C DLL并使用Java Invocation API在进程中创建一个Java VM,并从那里调用Java程序。这样,您就可以使用所需的任何入口点。JNA 在这里无济于事。