yglukhov / jnim

Nim - Java bridge
MIT License
184 stars 13 forks source link

[Q] Implementing Java native methods in Nim #57

Closed Anuken closed 4 years ago

Anuken commented 4 years ago

Is there a simple way to call Nim code in Java with native methods without passing around interface implementations? I looked around the examples and couldn't find any instances of this.

For example:

Java:

class TestJava{
    static native void runNim();

    static void runJava(){
        System.out.println("Running Java code.");
        runNim();
    }
}

Nim:

jclass TestClass of JVMObject:
    proc runNim(): void {.`static`.} =
        echo "Running Nim code."

    proc runJava() {.`static`.}

initJNI()

TestClass.runJava();

23 involves someone doing similar things, but low-level JNI stuff is being used there and I'm wondering if there's a simpler way to accomplish this.

akavel commented 4 years ago

What do you mean by "passing around interface implementations"? Is the example above what you have and works, or what you have and doesn't work, or what you would like to have? Could you give a (minimal ideally) sample of what works vs. what you would like to have?

I'm kinda experimenting with using jnim, so there's some chance I might try to help, but I don't know it nor JNI super well yet, which doesn't give me enough context to fully understand your question as you phrased it above... :(

Though if what I think you may be asking, can one implement native methods in Nim - then answer is yes; there are 2 ways: a) write a proc Java_com_anuken_helloworld_TestJava_runNim(...) and compile it with Nim to a .so, as if you were writing a regular JNI code in C - but with using jni types and macros as helpers; b) use jnim's jexport, but note it's still truly experimental / alpha quality (and I mean it).

yglukhov commented 4 years ago

@Anuken sorry, I missed your post, but generally what @akavel says. Either go low level as you would in C, or use jni_export. I'm biased towards the latter of course :). You can see some usage examples in the test https://github.com/yglukhov/jnim/blob/master/tests/test_jni_export.nim

Anuken commented 4 years ago

Thanks for the answer(s); looks like I missed the jni_export examples.