tags:

views:

157

answers:

1

Hi,

I have been struggling to find examples on void* example in JNA. I am trying to understand how to use Pointer in JNA.

For example

IN C :

int PTOsetApiOpt(int iOpt,void* lpValue,int iLen)

Parameters: iOpt: int
lpData: address from which data should be read.
iLen: length of data
returns int values : 0 as success or -1 as failure.

How do we write that in JAVA using JNA? I have tried this in JAVA

public MyTest{

 public interface MyLibrary extends Library {
   public int PTOsetApiOpt(int iOpt,Pointer lpValue,int iLen);

 }
 public static void main(String[] args) {
   MyLibrary myLib = (MyLibrary)MyLibrary.INSTANCE;
   int result = myLib.PTOsetApiOpt(1,new Pointer(0),1024);
 }

I get JVM crash when myLib.PTOsetApiOpt is invoked. I am guessing this is because of new Pointer statement. How can I create a Pointer and use it as parameter without JVM crash? I have been stuck on it for 2 days. Any tips would be great. Thanks in advance.

Regards, -Vid-

A: 

I think I have figured it out.

Here's how i wrote it in Java..

void* lpValue can be any type. So in C it is expecting address of int value.

 public MyTest{

 public interface MyLibrary extends Library {
   public int PTOsetApiOpt(int iOpt,Pointer lpValue,int iLen);

 }
 public static void main(String[] args) {
   MyLibrary myLib = (MyLibrary)MyLibrary.INSTANCE;
    IntByReference ir = new IntByReference(1);
    //got a result as 0 instead of -1.
    int result = myLib.PTOsetApiOpt(1, ir.getPointer() , ir.getPointer().SIZE);
 }