简体   繁体   中英

Return byte array from C# to Java using UnmanagedExports and JNA

I recently found the library UnmanagedExports that allowed me to access C#-methods directly from Java using JNA .

Has anyone an idea about what is wrong with my attempt to return a byte array from C# to Java?

Here is my example:

C# code:

using System;
using RGiesecke.DllExport;
namespace JnaTestLibrary
{
  public class JnaTest
  {
    [DllExport]
    public static byte[] returnT1()
    {
        byte[] t1 = {1,2,3,4,5};
        return t1;
    }
  }
}

Java code:

package me.mt.test;
import com.sun.jna.Library;
import com.sun.jna.Native;
import com.sun.jna.Platform;
public class JnaTest {
  public interface JnaTestInterface extends Library{
      byte[] returnT1();
  }
  static JnaTestInterface jnaTest = null;

  static{       
        if(Platform.is64Bit()){
            jnaTest = (JnaTestInterface)Native.loadLibrary("JnaTestLibrary64", JnaTestInterface.class);
        }
        else{
            jnaTest = (JnaTestInterface)Native.loadLibrary("JnaTestLibrary86", JnaTestInterface.class);
        }
    }

  public byte[] returnT1(){
      return jnaTest.returnT1();
  }
}

Java exception:

Exception in thread "main" java.lang.IllegalArgumentException: Unsupported return type class [I in function returnT1

I solved the problem by using pointers.

C# code:

using System;
using RGiesecke.DllExport;
namespace JnaTestLibrary
{
  public class JnaTest
  {
    [DllExport]
    public unsafe static byte* returnT1()
    {
        byte[] t1 = {1,2,3,4,5};
        fixed (byte* p1 = t1)
        {
          return p1;
        }
    }
  }
}

Java code:

package me.mt.test;
import com.sun.jna.Library;
import com.sun.jna.Native;
import com.sun.jna.Platform;
import com.sun.jna.Pointer;
public class JnaTest {
  public interface JnaTestInterface extends Library{
      Pointer returnT1();
  }
  static JnaTestInterface jnaTest = null;

  static{       
        if(Platform.is64Bit()){
            jnaTest = (JnaTestInterface)Native.loadLibrary("JnaTestLibrary64", JnaTestInterface.class);
        }
        else{
            jnaTest = (JnaTestInterface)Native.loadLibrary("JnaTestLibrary86", JnaTestInterface.class);
        }
    }

  public byte[] returnT1(){
      Pointer p1 = jnaTest.returnT1();
      return p1.getByteArray(0, 5);
  }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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