0

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 ?

osyan
  • 1,784
  • 2
  • 25
  • 54
  • You don't really give very much information here. Hard to know what your problem is. Although your attempts to return `std::string` are doomed to fail. What exactly is your question? – David Heffernan Jun 30 '14 at 10:16
  • @DavidHeffernan Hi David, i need to use my c++ code in java so i have to create a dll using JNI. My exact question is how to do this for C++ code **and not C**. because i had used c++ functioalities like `string` and etc – osyan Jun 30 '14 at 10:39
  • Please ask a direct and specific question in the question and not in the comments. And no, you won't be able to return `std::string` like that. I know you'd like to do so, but your desire to do so will not make it possible. It will be pure C style POD types across the DLL boundary. – David Heffernan Jun 30 '14 at 10:40
  • Please can you ask that in the question rather than comments. – David Heffernan Jun 30 '14 at 10:48
  • Let us [continue this discussion in chat](http://chat.stackoverflow.com/rooms/56532/discussion-between-osyan-and-david-heffernan). – osyan Jun 30 '14 at 11:12

1 Answers1

1

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());
}
David Heffernan
  • 601,492
  • 42
  • 1,072
  • 1,490