-2

I have the following C code. My aim is to call a C function from java.

C code:

_declspec(dllimport) BYTE __stdcall  CPSC1900Connect(BYTE port, void *param);



JNIEXPORT jbyte JNICALL Java_CPSE_CPSC1900Connect(JNIEnv * env, jclass hPrinter, jbyte port, jstring Answer)
{

     BYTE RC;

// I need to call CPSC1900Connect(BYTE port, void *param); function and pass (i DONT KNOW HOW TO PASS THOSE PAREMETER TO THIS METHOD.

//port and ANSWER PARAMETER. THE METHOD RETURNS BYTE WHICH I SHOULD BE VIED FROM JAVA

     return Answer;
}

java code:

public class CPSE {

   public  native byte CPSC1900Connect(byte port,String param);
   public  native String CPSC1900Disconnect(String param);
    static{

        try {

            System.loadLibrary("dll/CPSLPT9x");
            System.loadLibrary("dll/CPSRC");
            System.loadLibrary("dll/CPSE");
            System.loadLibrary("dll/MCHIP");


        } catch (Exception e) {
            System.out.println(e);
        }

    }

    public CPSE() {

        byte port=CPSC1900_USB;
                  param ="xx.xx.xx.xx"// ip address
         byte   response= CPSC1900Connect(BYTE port, void *param);


    }

    public static void main(String[] args)
    {
        new CPSE();

    }

}

My question is: How can I pass value from java application and pass it to the C function and get a response?

vefthym
  • 7,422
  • 6
  • 32
  • 58
NemugaM
  • 11
  • 5
  • I have done JNI using this [tutorial](http://www.ibm.com/developerworks/java/tutorials/j-jni/j-jni.html). It will solve your problem. – Ajith John Jul 01 '15 at 12:49
  • @Ajith John My greatest problem is how to pass values to the function and returning inform of byte – NemugaM Jul 01 '15 at 12:57

1 Answers1

0

Have you tried the the straightforward implementation?

JNIEXPORT jbyte JNICALL Java_CPSE_CPSC1900Connect(JNIEnv * env, jclass hPrinter, jbyte port, jstring Answer)
{

    const char* param = (*env)->GetStringUTFChars(env, Answer, 0);
    jbyte res = (jbyte)CPSC1900Connect((BYTE)port, (void*)param);

    (*env)->ReleaseStringUTFChars(env, Answer, param);

    return res;
}

This assume the void* param of CPSC1900Connect is read only, otherwise copy the param string to a local buffer.

I have not compiled this code, just wrote it. Do basic corrections if needed.

  • am getting -80 from java but wanted respond like 0xB0. Kindly assist. – NemugaM Jul 01 '15 at 13:29
  • @NemugaM that's because java bytes are signed. `0xb0` *is* -80 in 8bit two complement. you are getting the expected value. –  Jul 01 '15 at 13:46
  • how can I convert it to 0xb0 – NemugaM Jul 01 '15 at 13:54
  • either substitute every `jbyte` (except `jbyte port`) with `jint` and update your Java definition accordingly ( so that the java method return an `int`) or see this [answer](http://stackoverflow.com/questions/7401550/how-to-convert-int-to-unsigned-byte-and-back#7401635). –  Jul 01 '15 at 15:17