I have some Java methods that I need to call from C++ via JNI. My JNI implementation is based on
Is it possible to make a Java JNI which calls jdbc?
There are two java files in my Java project. One is to define a class, and the other one contains the actual methods that c++ will call.
public class MyObject {
private static int no;
private static LocalDateTime time;
private static String status;
// getters, setters and toString
}
public class ObjectHandler {
public static MyObject objectReturnToC;
public static Object methodA (type1 arg1, type2 arg2, type3 arg3) {
objectReturnToC = new MyObject();
// setting fields in returnObject according to passed-in parameters
return objectReturnToC;
}
public static void methodB(Object objectReturnedFromC) {
// access fields in objectReturnedFromC, do computation and store in
}
}
I created C++ DLL in Visual Studio 2010. There's JVM.cpp, JVM.h, JavaCalls.h, and JavaCalls.cpp
JavaCalls.h
#ifdef JAVACALLSDLL_EXPORTS
#define JAVACALLSDLL_API __declspec(dllexport)
#else
#define JAVACALLSDLL_API __declspec(dllimport)
#endif
namespace JavaCalls
{
class JavaCalls
{
public:
static JAVACALLSDLL_API void *javaMethodA(type1, type2, type3);
static JAVACALLSDLL_API string toString(void **javaObject);
static JAVACALLSDLL_API void javaMethodB(void **javaObject);
};
}
JavaCalls.cpp
namespace JavaCalls
{
void *JavaCalls::javaMethodA(type1 arg1, type2 arg2, type3 arg3)
{
// invoke JVM
// Find class, methodID
jobject javaObject = CallStaticObjectMethod(jMain, "methodA",...);
return javaObject;
}
void JavaCalls::javaMethodB(void** javaObject) {
// invoke JVM
// Find class, methodID
CallStaticVoidMethod(jMain, "methodB",...);
}
}
C++ calling Java methodA and methodB using DLL:
int main()
{
void* a = JavaCalls::JavaCalls::javaMethodA(arg1, arg2, arg3);
// doing other stuff and updating fields in a
JavaCalls::JavaCalls::javaMethodB(static_cast<void**>(a));
}
Obviously, passing pointer, wishing it would be available to C++ is not working. But what should I do to keep the Java Object in C++ and pass it back to Java later? Should I create a C++ struct and map Java Object field into it using GetObjectField?