public class SMPL1 { private native int DxOpenPort( String com, int br ); private native boolean DxClosePort( int devid ); private native boolean DxPing( int devid, int uid, int tout, char[] terr ); static { System.loadLibrary( "dxtest" ); // 今回作成するラッピング用DLL(dxtest.dll) } public static void main( String args[] ) { String COMPORT = "\\\\.\\COM3"; // COMポート名 int BUADRATE = 1000000; // ボーレート int TIMEOUT = 50; // タイムアウト char terr[] = new char[1]; int devid, i; String msg = "Ping to ID:", mrk = "\n"; SMPL1 me = new SMPL1(); devid = me.DxOpenPort( COMPORT, BUADRATE ); if ( devid != 0 ) { for ( i = 0; i < 253; i++ ) { if ( me.DxPing( devid, i, TIMEOUT, terr ) ) { System.out.printf( "\nPing to ID:%d...OK", i ); mrk = "\n"; } else { System.out.printf( "%sPing to ID:%d...NG(%x)", mrk, i, (int)terr[0] ); mrk = "\r"; } } if ( !me.DxClosePort( devid ) ) System.out.printf( "Close error\n" ); } else System.out.printf( "Port not open\n" ); } } |
>javac SMPL1.java |
>javah -classpath . -d . SMPL1 |
JNIEXPORT jint JNICALL Java_SMPL1_DxOpenPort (JNIEnv *, jobject, jstring, jint); JNIEXPORT jboolean JNICALL Java_SMPL1_DxClosePort (JNIEnv *, jobject, jint); JNIEXPORT jboolean JNICALL Java_SMPL1_DxPing (JNIEnv *, jobject, jint, jint, jint, jcharArray) |
#define __MAKE_LIB__ #include <stdio.h> #include <stdlib.h> #include <jni.h> #include "dxlib2.h" JNIEXPORT jint JNICALL Java_SMPL1_DxOpenPort (JNIEnv *env, jobject jobj, jstring pCom, jint br) { DXDEVICEID dev; char *port; int sz = (*env)->GetStringLength( env, pCom ); // java文字列より取得 const char *comPort = (*env)->GetStringUTFChars( env, pCom, 0 ); port = (char *)malloc( sz + 1 ); strcpy( port, comPort ); port[strlen(port)] = 0x0; dev = DX_OpenPort( port, br ); // dxlib2.dllのDX_OpenPort()の呼出し // memory解放 free( port ); (*env)->ReleaseStringUTFChars( env, pCom, comPort ); return (jint)dev; } JNIEXPORT jboolean JNICALL Java_SMPL1_DxClosePort (JNIEnv *env, jobject jobj, jint id) { return DX_ClosePort( (DXDEVICEID)id ); } JNIEXPORT jboolean JNICALL Java_SMPL1_DxPing (JNIEnv *env, jobject jobj, jint devid, jint id, jint tout, jcharArray terr) { TDxErrorCode err; BOOL bResult; UCHAR uID; jchar *arrays; // local領域 int sz; // 配列size jboolean jbl; // isCopy uID = (UCHAR)(id & 0x00ff); bResult = DX_Ping( (DXDEVICEID)devid, uID, tout, &err ); // 配列の取得 arrays = (*env)->GetCharArrayElements( env, terr, &jbl ); if ( (*env)->GetArrayLength( env, terr ) > 0 ) arrays[0] = err; // 配列の解放(Javaへ適用) (*env)->ReleaseCharArrayElements( env, terr, arrays, 0 ); return bResult; } |
>gcc -shared -o dxtest.dll dxtest.c -l dxlib2 -Wl,-kill-at -I Javaのincludeパス -I Javaのincludeパス\win32 -L . |
SMPL1.class dxtest.dll dxlib2.dll |
>java SMPL1 |