javacnativejnajnaerator

use Pointer address in Java using Bridj and JNAerator


I have this code in C and I would like to write the same in Java:

static u_int32_t print_pkt (struct nfq_data *tb){
    unsigned char *data;
    ret = nfq_get_payload(tb, &data);
    if (ret >= 0)
        printf("payload_len=%d ", ret);
    printf("data: ");
    for(i=0;i<ret;i++){
        printf("%c",data[i]);
    }
    fputc('\n', stdout);
    return ret;
}

I used JNAerator to create the fonctions in Java that will call the C fonction nfq_get_payload using Bridj (Mylib Class):

public static int nfq_get_payload(Pointer<Netfilter_queueLibrary.nfq_data > nfad, Pointer<Pointer<Byte > > data) {
    return nfq_get_payload(Pointer.getPeer(nfad), Pointer.getPeer(data));
}
protected native static int nfq_get_payload(@Ptr long nfad, @Ptr long data);

My "equivalent" Java code is:

static int print_pkt (Pointer< nfq_data > tb)
{
    int ret;
    Pointer<Byte> data =null;
    ret = MyLib.nfq_get_payload(tb, Pointer.pointerToPointer(data));
    if (ret >= 0){
        System.out.println(String.format(" payload_len=%d ", ret));
        System.out.print("data: ");
        for(int i=0;i<ret;i++){
            System.out.print(data.get(i));
        }
    }
    System.out.println();

    return ret;
}

I should mention that the ret value is the same when using c code and java code, but when I try to access data, a NullPointerException is raised when using Java (in C code I get something else that I excepect). When I do Pointer<Byte> data =Pointer.allocateBytes(4096); I get zeros instead of the null pointer Exception, but since I don't allocate memory in C code I think I shouldn't do it also in Java code.

Thank you for your time and your help Cheers


Solution

  • I finnaly found a fix this way, and still don't know why the first one doesn't work:

    val data2 = Pointer.pointerToPointer(data);
    ret = Netfilter_queueLibrary.nfq_get_payload(tb, data2)
    if (ret >= 0) {
      println(String.format(" payload_len=%d ", ret));
      println("data: ");
      for (i <- 0 until ret) {
        printf("%02x", (data2.get().getBytes(ret)(i)));
      }
    

    hope it will help someone