I have coded the following for numerical integration in C++:
// integrate.h:
#ifdef BUILDING_DLL
#define DLL_MACRO __declspec(dllexport)
#else
#define DLL_MACRO __declspec(dllimport)
#endif
extern "C" {
typedef double (*Function1VariablePtr)(double x);
double DLL_MACRO integrate(Function1VariablePtr function, double min, double max);
}
// integrate.cpp:
#include "integrate.h"
double integrate(Function1VariablePtr function, double min, double max) {
const int n = 1001;
double dx = (max - min)/(1.0*(n - 1));
double sum = 0.0;
for(int i = 0; i < n; i++) {
double xmid = min + (i + 0.5)*dx;
sum += function(xmid)*dx;
}
return sum;
}
Now I want to call this function from Java. I found how I can implement the integration directly in the JNI "bridge" code:
// C++ "bridge" code to from/to Java:
JNIEXPORT jdouble JNICALL
Java_IntegrateJApp_JIntegrate(JNIEnv *jnienv, jclass jc,
jdouble xmin, jdouble xmax) {
jmethodID mid = jnienv->GetStaticMethodID(jc, "Function1D","(D)D");
if (mid == 0)
return - 1.0;
const int n = 1001;
double dx = (xmax - xmin)/(1.0*(n - 1));
double sum = 0.0;
for(int i = 0; i < n; i++) {
double xmid = xmin + (i + 0.5)*dx;
double f = jnienv->CallStaticDoubleMethod(jc, mid, xmid);
sum += f*dx;
}
return sum;
}
// Java code calling "bridge":
class IntegrateJApp {
public static void main(String[] args) {
System.loadLibrary("JIntegrate");
double I = JIntegrate(0.0, 2*Math.PI);
System.out.println( Double.toString(I) );
}
public static double Function1D(double x) {
return Math.sin(x);
}
public static native double JIntegrate(double xmin, double xmax);
}
However I do not want to implement the numeric integration directly in the C++ bridge code, but rather call the code in integrate.cpp.
How do I do this? The integrate() function inside integrate.cpp requires a function pointer which I do not have. Is there a way to get a pointer to a function inside Java using JNI?
Thanks in advance for any answers!