So I need to use JNI to call a C function from java. I've been able to successfully do this when passing in different data types (create the native variables, header file, shared library, blah blah), but can't get it to work with a byte array. Here's my C function:
#include <stdio.h>
void encrypt(int size, unsigned char *buffer);
void decrypt(int size, unsigned char *buffer);
void encrypt(int size, unsigned char *buffer){
for(int i=0; i<size; i++){
unsigned char c = buffer[i];
printf("%c",c);
}
}
void decrypt(int size, unsigned char *buffer){
for(int i=0; i<size; i++){
unsigned char c = buffer[i];
printf("%c",c);
}
}
And here's my java code (I understand that after making a header file from this, I have to replace the C function declarations by the JNI code in the header file)
class Tester{
public native void encrypt(int size, char *buffer);
public native void decrypt(int size, char *buffer);
static{
System.loadLibrary("buffer");
{
public static void main(String[] args){
Tester test = new Tester();
String hello = "hello";
byte[] byteHello = hello.getBytes();
test.encrypt(5,byteHello);
test.decrypt(5,byteHello);
}
}
I get that the char* type isn't supported in Java and that's why I'm getting an error trying to compile. Perhaps I should change the type to char[] in Java? Anyways, my goal is to be able to pass a byte array in Java into my C function, iterate through the byte array, and print out each element.
charand Cchartypes are incompatible, it would probably be better to pass thebyte[]to C and then convert each element on demand