【Java】【C】【C++】 JNA [2] ~ 基本編 ~

■ はじめに

https://blogs.yahoo.co.jp/dk521123/36187289.html
の続き。

C言語の構造体をやり取りを扱う。

■ サンプル

環境

 * OS : CentOS7
 * Java : JDK 1.8.0_133
 * JNA : Version 4.4.0

C側

Sample.c
#include <stdio.h>
#include <stdlib.h>

typedef struct
{
  long id;
  char* name;
  int age;
} Person;

int getPerson(Person** person)
{
  *person = (Person *) malloc (sizeof(Person *));

  (*person)->id = 1;
  (*person)->name = "Mike";
  (*person)->age = 23;

  return 0;
}

int freePerson(Person** targetPerson)
{
  Person *person = *targetPerson;
  free(person);

  return 0;
}
gcc -fPIC -shared -o libSample.so Sample.c」でコンパイルする

Java

ISample.java
import com.sun.jna.Library;
import com.sun.jna.Native;
import com.sun.jna.ptr.PointerByReference;

public interface ISample extends Library {
  // インスタンス生成
  ISample INSTANCE = (ISample) Native.loadLibrary("/home/admin/workspace/Demo/etc/libSample.so", ISample.class);

  int getPerson(PointerByReference result);

  int freePerson(PointerByReference people);
}
Person.java
import java.util.Arrays;
import java.util.List;

import com.sun.jna.Pointer;
import com.sun.jna.Structure;

public class Person extends Structure implements Structure.ByReference {
  public long id;
  public String name;
  public int age;
  
  public Person() {
  }

  public Person(Pointer pointer) {
      super(pointer);
      read();
  }
  @Override
  protected List<String> getFieldOrder() {
    return Arrays.asList("id", "name", "age");
  }
}
Main.java
import com.sun.jna.Pointer;
import com.sun.jna.ptr.PointerByReference;

public class Main {

  public static void main(String[] args) {
    ISample sample = ISample.INSTANCE;
    PointerByReference result = new PointerByReference();
    int resultCode = sample.getPerson(result);
    Pointer resultPointer = result.getValue();
    Person person = new Person(resultPointer);
    System.out.println("[Java Code] resultCode = " + resultCode);
    System.out.println("[Java Code] ID = " + person.id);
    System.out.println("[Java Code] Name = " + person.name);
    System.out.println("[Java Code] Age = " + person.age);
    
    resultCode =  sample.freePerson(result);
    System.out.println("[Java Code] resultCode = " + resultCode);
    System.out.println("[Java Code] DONE!!");
  }
}

出力結果

[Java Code] resultCode = 0
[Java Code] ID = 1
[Java Code] Name = Mike
[Java Code] Age = 23
[Java Code] resultCode = 0
[Java Code] DONE!!