JNAを使用してJavaから呼び出そうとしているCの関数があります。
int myCfunc(void *s, int *ls);
JNAのドキュメントによると、void*はcom.sun.jna.Pointer
関数に渡される必要があります。JNAを使用するJavaでは、上記の関数は次のようにラップされると思います。
public interface myWrapper extends Library{
public int myCfunc(Pointer s, IntByReference ls);
}
ポインタにリンクし、パラメータs
を渡す必要があるオブジェクトは、次のようなJNA構造を実装するクラスになります。
public class myClass extends Structure{
public int x;
public int y;
public int z;
}
残念ながら、パラメータls
はクラスの長さをバイト単位で表す整数です。Javaには関数がないsizeof
ため、これにより複雑さが増します。私が抱えているもう1つの大きな問題は、オブジェクトの内容をネイティブメモリに正しく渡したり戻したりしていることを確認することです。
私のコードは次のようになります。
import com.sun.jna.Native;
import com.sun.jna.Pointer;
import com.sun.jna.Structure;
import com.sun.jna.ptr.IntByReference;
public void foo(){
myWrapper wrapper = (myWrapper) Native.loadLibrary("SomeDllWithLegacyCode", myWrapper.class);
myClass myObj = new myClass();
myObj.x = 1;
myObj.y = 2;
Pointer myPointer = myObj.getPointer();
int size = Native.getNativeSize(myClass.class);
IntByReference len = new IntByReference(size);
myObj.write(); //is this required to write the values in myObj into the native memory??
wrapper.myCfunc(myPointer, len);
myObj.read(); //does this read in the native memory and push the values into myObj??
myPointer.clear(size); //is this required to clear the memory and release the Pointer to the GC??
}
渡されたデータのサイズがC関数で予想されるよりも大きいというエラーが発生します。
上記のコードは、同様の問題を扱っている質問に対するこの回答で提供されているのとほぼ同じ種類の手順に従いますが、C#です。私はそれがC#で動作することを試し、テストしました。
私の質問はStackoverflowの別の質問と似ていますが、クラスへのポインターではなく、IntByReferenceへのポインターを扱います。