使用JNA分配字节数组

时间:2010-12-11 02:07:49

标签: arrays pointers char jna

我正在尝试开发一个函数来填充作为实际参数传递的字节数组。我正在关注JNA文档的示例,但它无法正常工作。文档说:

// Original C declaration allocate_buffer <br>
void (char ** bufp, int * lenp);

// Equivalent JNA mapping
void allocate_buffer (PointerByReference bufp, IntByReference lenp);

// Usage
PointerByReference PointerByReference pref = new ();
IntByReference IntByReference iref = new ();
lib.allocate_buffer (pref, iref);
Pref.getValue Pointer p = ();
byte [] buffer = p.getByteArray (0, iref.getValue ());

我在C中的功能是:

__declspec (dllexport) void allocate_buffer (char ** bufp, int * lenp)
{
    char array [4];

    array [0] = 0;
    array [2] = 1;
    array [3] = 2;
    array [4] = 3;

    * bufp = array;
    * lenp = 4;
}

但是当打印数组值时会得到结果: 0 20 48 2

如何正确实现allocate_buffer函数? 或问题是Java代码?

谢谢!

1 个答案:

答案 0 :(得分:0)

解决: 正确的C函数是:

__ declspec(dllexport)void allocate_buffer(unsigned char * bufp,int lenp)

{

    unsigned char *array = (unsigned char *)malloc(4*sizeof(unsigned char));

    array[0] = 0;
    array[1] = 1;
    array[2] = 2;
    array[3] = 3;

    *bufp = array;
    *lenp = 4;

}