-2

I ran into a problem with return jobject.

I have class:

 class KeyPair  {

        std::vector<BYTE> _publicKey;
        std::vector<BYTE> _privateKey;

    public:
        void SetKeys(std::vector<BYTE> publicKey, std::vector<BYTE> privateKey)
        {
            _publicKey = publicKey;
            _privateKey = privateKey;
        };
    };

and function:

JNIEXPORT jobject JNICALL function(JNIEnv *env, jobject)
{
    //some code
    KeyPair keyPair;
    keyPair.SetKeys(pub, priv);
    return keyPair;//error
}

How can i return keyPair as jobjecct?

  • Welcome to JNI. The workflow is to define a Java class, mark some methods as native, run javac to get a .class file, run javah to get a .h file, and then implement the functions in a compatible language based on the .h file. You might find javap -s useful when calling JNI functions. Also, consider SWiG and JNA as JNI tools that do the workflow in the opposite direction. SWiG might serve you best here. – Tom Blodget Sep 24 '17 at 15:57

2 Answers2

0

Can you paste here the error? Actually, you can not return a class - it just doesn't make sense, you always return an object, that is an instance of the class.

ibnLoki
  • 35
  • 6
0

You cannot cast C++ objects to jobjects like that.

One approach is to define a Java KeyPair class that has a private long ptr field into which you stuff a pointer to a C++ KeyPair object. It helps if you create a one-argument constructor that fills the ptr field with its argument.

To create such a thing: (see also How to create an object with JNI?)

  • Look up the jclass associated with your java KeyPair class (env->FindClass).
  • Look up the constructor (env->GetMethodId).
  • Instantiate the object (env->NewObject).
  • Finally, return the jobject.

If you later need to extract the ptr from a KeyPair passed as jobject, you need to look up the field ID for ptr and use env->GetLongField to extract it.

Botje
  • 26,269
  • 3
  • 31
  • 41