10

我在 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 的指针,而不是指向类的指针。

4

1 回答 1

6

首先,JNA 自动处理它自己的内存分配,这意味着下面的行是无用的(并且可能会损坏内存堆栈):

myPointer.clear(size); //is this required to clear the memory and release the Pointer to the GC??

接下来它还会自动处理本机指针类型,这意味着下面的两行在您的情况下是等效的:

public int myCfunc(Pointer s, IntByReference ls);
public int myCfunc(myClass s, IntByReference ls);

因此,JNA 会 myObj.write();read您做。

以下内容 100% 正确,但我建议您len.getValue()在调用之前和之后记录myCfunc(这将给出 3*4=12 ;3 int of 4 bytes):

int size = Native.getNativeSize(myClass.class);
IntByReference len = new IntByReference(size);

如果所有这些都是正确的,那么您的结构原型中可能有错误。

根据我的经验,这主要是由于过时的 C 头文件或过时的库:

  • 您使用的是标头版本 2.0,它声明结构的值是 int,但是您链接到库 v1.0,它采用字节结构
  • 您使用的是标头版本 2.0,它声明结构的值是 int,但是您链接到库 v1.9,它需要两个整数和一个字节

最后你的代码应该是这样的:

public void foo(){
    myWrapper wrapper = (myWrapper) Native.loadLibrary("SomeDllWithLegacyCode", myWrapper.class);

    myClass myObj = new myClass();
    myObj.x = 1;
    myObj.y = 2;

    int size = Native.getNativeSize(myClass.class);
    IntByReference len = new IntByReference(size);

    //log len.getValue
    wrapper.myCfunc(myObj, len);
    //log len.getValue
}

您还可以尝试出于调试目的自愿降低 len 的值,例如:

IntByReference len = new IntByReference(size-1);
IntByReference len = new IntByReference(size-2);
IntByReference len = new IntByReference(size-3);
//...
IntByReference len = new IntByReference(size-11);

这不会做你不想要的,但至少它应该给你正确的“max len”

于 2010-12-24T14:24:59.803 回答