简体   繁体   English

使用 JNI 从 Java 调用 C 函数

[英]Calling C function from java using JNI

I have the following C code.我有以下 C 代码。 My aim is to call a C function from java.我的目标是从 java 调用 C 函数。

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?我的问题是:如何从 Java 应用程序传递值并将其传递给 C 函数并获得响应?

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.这假设CPSC1900Connectvoid* param是只读的,否则将param字符串复制到本地缓冲区。

I have not compiled this code , just wrote it.我没有编译这段代码,只是写了它。 Do basic corrections if needed.如果需要,请进行基本更正。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM