まず javah 等で自動生成したヘッダーファイルとなります。
com_book_jni_HelloJNI.h.
/* DO NOT EDIT THIS FILE - it is machine generated */
#include <jni.h>
/* Header for class com_book_jni_HelloJNI */
#ifndef _Included_com_book_jni_HelloJNI
#define _Included_com_book_jni_HelloJNI
#ifdef __cplusplus
extern "C" {
#endif
/*
* Class: com_book_jni_HelloJNI
* Method: sayHello
* Signature: ()V
*/
JNIEXPORT void JNICALL Java_com_book_jni_HelloJNI_sayHello
(JNIEnv *, jobject);
/*
* Class: com_book_jni_HelloJNI
* Method: checkDevice
* Signature: ()V
*/
JNIEXPORT void JNICALL Java_com_book_jni_HelloJNI_checkDevice
(JNIEnv *, jobject);
#ifdef __cplusplus
}
#endif
#endif
次にヘッダーファイルを実装します。
実装には OpenCL の C 言語の API を使うため、C 言語での OpenCL アプリケーションの実装の知識が必要となります。
本書では C 言語での説明は割愛しますので、興味があるなら拙著の C 言語バージョンを参照ください。
com_book_jni_HelloJNI.c.
#include <jni.h>
#include <stdio.h>
#include "com_book_jni_HelloJNI.h"
#include <OpenCL/cl.h>
JNIEXPORT void JNICALL Java_com_book_jni_HelloJNI_checkDevice(
JNIEnv *env, jobject thisObj) {
cl_platform_id platform;
cl_device_id *devices;
cl_uint num_devices, addr_data;
cl_int i, err;
char name_data[48], ext_data[4096];
err = clGetPlatformIDs(1,
&platform, NULL);
if(err < 0) {
perror("failed to find platforms");
exit(1);
}
err = clGetDeviceIDs(platform,
CL_DEVICE_TYPE_ALL,
1, NULL, &num_devices);
if(err < 0) {
perror("Failed to find devices");
exit(1);
}
devices = (cl_device_id*)
malloc(sizeof(cl_device_id) * num_devices);
clGetDeviceIDs(platform,
CL_DEVICE_TYPE_ALL,
num_devices,
devices, NULL);
for(i=0; i<num_devices; i++) {
err = clGetDeviceInfo(devices[i],
CL_DEVICE_NAME,
sizeof(name_data), name_data, NULL);
if(err < 0) {
perror("Failed to read device name");
exit(1);
}
printf("CL_DEVICE_NAME: %s\n",name_data);
clReleaseDevice(devices[i]);
}
free(devices);
}
Java_com_book_jni_HelloJNI_checkDevice() 関数は OpenCL が使えるデバイスのクエリーをして、見つかったデバイスを標準出力します。
Copyright 2018-2019, by Masaki Komatsu