Search code examples
javac++cjnaentry-point

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


I was fooling around with JNA trying to execute some C code in a Java program. This is a working example I found online (JNA required in build path):

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, World\n");
        for (int i = 0; i < args.length; i++) {
            CLibrary.INSTANCE.printf("Argument %d: %s\n", i, args[i]);
        }

        Native.main(args);
    }
}

Actually, I am trying to do three (seemingly rediculess) things.

1.) The entry point of the program should be changed to the following C signature:

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

2.) The Java program should be able set the given output parameter.
3.) The program should be compiled to a DLL.

In C++, this issue would be resolved like this:

#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);
}

So the question is, is that somehow possible with Java? If so, I'd be glad to see some code example as I am entery a lot of new territory here. I don't even know if JNA is a proper solution here. If anyone has another idea, please tell!

Kind regards,
jaySon


Solution

  • You'd have to write a regular C DLL and use the Java Invocation API to create a Java VM inside the process and call your Java program from there. That way you can use any entry point you want. JNA doesn't help here.