简体   繁体   English

JNA的Void *示例

[英]Void* example for JNA

I have been struggling to find examples on void* example in JNA. 我一直在努力寻找JNA上关于void *示例的示例。 I am trying to understand how to use Pointer in JNA. 我试图了解如何在JNA中使用Pointer。

For example 例如

IN C : 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? 我们如何使用JNA在JAVA中编写代码? I have tried this in JAVA 我在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. 调用myLib.PTOsetApiOpt时,JVM崩溃。 I am guessing this is because of new Pointer statement. 我猜这是因为新的Pointer语句。 How can I create a Pointer and use it as parameter without JVM crash? 如何创建Pointer并将其用作参数而不会导致JVM崩溃? I have been stuck on it for 2 days. 我已经坚持了两天。 Any tips would be great. 任何提示都很好。 Thanks in advance. 提前致谢。

Regards, -Vid- 问候,-Vid-

声明您的方法以IntByReference作为参数,然后在调用该方法时不必调用ByReference.getPoint()。

I think I have figured it out. 我想我已经知道了。

Here's how i wrote it in Java.. 这是我用Java编写的方式。

void* lpValue can be any type. void * lpValue可以是任何类型。 So in C it is expecting address of int value. 因此,在C中,它期望的是int值的地址。

 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);
 }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM