osyan
osyan

Reputation: 1866

Best way to send parameter between JNI and C++

I had wrote my program using visual studio c++ and now i'm trying to create a dll from that code to use in another java application. For example i have a two function in c++:

int  __declspec(dllexport) _stdcall   login(const unsigned char pin[4])

and

string __declspec(dllexport) _stdcall RNG_Gen (unsigned char* data)

Then i followed the instruction of some webpage on how to create a DLL from C++ code for java using JNI, so i include "jni.h" and wrote another function like this to call my function:

for the first function i use :

#define JNIEXPORT __declspec(dllexport)
#define JNIIMPORT __declspec(dllimport)
#define JNICALL __stdcall

JNIEXPORT jint JNICALL Java_login
  (JNIEnv *env, jobject obj, jbyteArray pin)
 {
    int len = env->GetArrayLength (pin);
        if(len<PIN_SIZE)return -1;
        unsigned char buf[4];// = new unsigned char[len];
    env->GetByteArrayRegion (pin, 0, len, (jbyte *)(buf));
        return login(buf);

 }

But what should i do with string and unsigned char* in the second function? how should i call that function? how should i send an unsigned char * to that function? and how can i get the returned string ?

Upvotes: 0

Views: 395

Answers (1)

David Heffernan
David Heffernan

Reputation: 613202

You've already worked out how to use jbyteArray for the unsigned char* parameter. You do just what you did with the login function, calling GetArrayLength and GetByteArrayRegion. No need for me to repeat that here.

For the string return value you need to use jstring, like this:

JNIEXPORT jstring JNICALL Java_RNG_Gen
    (JNIEnv *env, jobject obj, jbyteArray data) 
{
     // do whatever is needed to obtain the result string
     std::string result = ...; 

     // create a new jstring value, and return it
     return env->NewStringUTF(result.c_str());
}

Upvotes: 1

Related Questions