我有在C函数,我试图从Java与JNA拨打:传递一个Java类转换为一个void *参数与JNA
int myCfunc(void *s, int *ls);
按照JNA documentation虚空*需要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
函数,所以这增加了一点额外的复杂性。 我遇到的另一个主要问题是确保将对象的内容正确传递给本机内存并返回。
我的代码是类似以下内容:
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函数。
上述代码粗略地遵循相同类型的步骤as provided out in this answer来处理类似问题,但在C#中。我试过并测试过它可以在C#中使用。
我的问题类似于another on Stackoverflow,但它处理的是指向IntByReference的指针,而不是指向类的指针。