简体   繁体   English

Java中的Java jbytearray访问(JNI)

[英]Java jbytearray access in c (JNI)

I have a set of java classes that I need at my job to be ran in C/C++. 我有一组在我的工作中需要在C / C ++中运行的java类。

And, since I am fairly new to java, I am taking it one step at a time. 而且,由于我对java很新,所以我一步一个脚印。 I've gotten to be able to call java with string, int double etc, but the end results will be getting a byte array back (a pdf document) so I tried sending back a simple two element byte array. 我已经能够用string,int double等调用java了,但是最终结果将得到一个字节数组(pdf文档)所以我试着发回一个简单的两个元素字节数组。

Here is the java: 这是java:

public class ReturnData
{
    int returnValue;
    String Log;
    Byte[] data = new Byte[2];

     public ReturnData(int nRetVal, String szLog)
     {
         this.data[0] = 100;
         this.data[1] = 12;
         this.returnValue = nRetVal;
         this.Log = szLog;
     }
}

and here is the c++ code (JNI initialization removed. It works for simple types so ...) 这里是c ++代码(删除了JNI初始化。它适用于简单类型,所以......)

jbyteArray jbyteData = (jbyteArray)jniEnvironment->GetObjectField(jobjRetData,
    jniEnvironment->GetFieldID(clsReturn, "data", "Ljava/lang/ByteArray;"));

And now anytime I access the jbyteData element, such as: 现在我随时都可以访问jbyteData元素,例如:

jsize len = jniEnvironment->GetArrayLength(jbyteData);

I get an Exception 我得到一个例外

System.AccessViolationException was unhandled
Message: Attempted to read or write protected memory. This is often an indication that other 
memory is corrupt.

Try to change the field Byte[] data = new Byte[2]; 尝试更改字段Byte[] data = new Byte[2]; to byte[] data = new byte[2]; to byte[] data = new byte[2];

Then in your JNI method use GetFieldID(clsReturn, "data", "[B")); 然后在你的JNI方法中使用GetFieldID(clsReturn, "data", "[B"));

Edit: To be able to get the internal signature of each type ( [B for byte[] in your case) you can declare the field you want to a class (let's call it Test ), compile it and then run javap -s Test . 编辑:为了能够获得每种类型的内部签名(在你的情况下[Bbyte[] )你可以声明你想要一个类的字段(让我们称之为Test ),编译它然后运行javap -s Test It produces an output like below: 它产生如下输出:

Compiled from "SimpleMain.java"
public class SimpleMain extends java.lang.Object{
public byte[] data;
  Signature: [B            // <-- signature shows the internal type 
public SimpleMain();
  Signature: ()V
public static void main(java.lang.String[]);
  Signature: ([Ljava/lang/String;)V
}

For the FieldID, I think you want to use "[B" instead of "Ljava/lang/ByteArray;" 对于FieldID,我认为你想使用"[B"而不是"Ljava/lang/ByteArray;" , which isn't actually a class. ,实际上不是一个班级。

Edit: since you're using the Byte class, which I missed in my original response, use " [Ljava/lang/Byte;" 编辑:因为您正在使用我在原始响应中遗漏的Byte类,请使用“ [Ljava/lang/Byte;" instead 代替

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

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