0

I am attempting to call a Java method which accepts a lambda as an argument. I am not in control of the Java side of the code, and am using the invocation API. I do not know how I would even start to approach this problem- from my searches, lambdas are compile-time language artifacts of Java. That also links this answer which shows how to make a lambda at runtime. Is creating a lambda possible to do in JNI, and if so how do you pass this into a method call?

majorsopa
  • 75
  • 9
  • Please edit your question with the signature of the Java method you are trying to pass a lambda to. – Botje Jan 30 '23 at 09:41
  • @Botje It is an obfuscated signature so I'm not sure how much help it would be to others. – majorsopa Jan 30 '23 at 21:49
  • It would help because methods generally don't take "lambdas". They take objects that implement a given interface and lambdas are just a shortcut for constricting suitable objects. If we know the exact signature of the method the translation to a native method is mechanical. – Botje Jan 31 '23 at 08:01

1 Answers1

1

Let me take LongStream.generate as an example target method. Its method signature is

static LongStream generate(LongSupplier s);

and LongSupplier is:

@FunctionalInterface public interface LongSupplier {
  long getAsLong();
}

You can implement your own LongSupplier on the Java side as follows:

package dummy.pkg;
import java.util.function.LongSupplier;
public class NativeLongSupplier implements LongSupplier {
  native public long getAsLong();
}

then the following C++ code will let you implement the getAsLong method:

JNIEXPORT jlong Java_dummy_pkg_NativeLongSupplier_getAsLong(JNIEnv * env, jobject obj) {
  static uint64_t counter = 0;
  return ++counter;
}
Botje
  • 26,269
  • 3
  • 31
  • 41