我有以下C代码。我的目标是从java调用C函数。
C代码:
_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代码:
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();
}
}
我的问题是:如何从java应用程序传递值并将其传递给C函数并获得响应?
答案 0 :(得分:0)
您是否尝试过直接的实施?
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;
}
这假设void* param
的{{1}}是只读的,否则将CPSC1900Connect
字符串复制到本地缓冲区。
我还没有编译这段代码,只是写了它。如果需要,进行基本修正。