我在 C 中有一个函数,我试图用JNA从 Java 调用它:
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);
}
需要链接到Pointer并传入参数的对象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 函数预期的要大。
上面的代码大致遵循与处理类似问题的问题的答案中提供的相同类型的步骤,但在 C# 中。我已经尝试并测试它在 C# 中工作。
我的问题类似于Stackoverflow 上的另一个问题,但它处理的是指向 IntByReference 的指针,而不是指向类的指针。