How to call existing c ++ dll from java

I have one C ++ dll that was previously used for a C # application. now we want to use the same DLL for java. i know we can use JNI technology for this, but the problem is that we have to use the same method signature, we don't want to change the singularity method. please tell me.

+3


source to share


2 answers


One option uses JNA instead of JNI. This removes the need for your own template code. An example would look something like this:



import com.sun.jna.Library;
import com.sun.jna.Native;

public class Example {

  public interface NativeMath extends Library {

    public bool isPrime(int x);
  }

  public static void main(String[] args) {

    int x = 83;

    NativeMath nm = (NativeMath) Native.loadLibrary("nm", NativeMath.class);

    System.out.println(x + " is prime: " + nm.isPrime(x));
  }
}

      

+1


source


You don't need to change the method signature, you just add your own method, which then calls the native C ++ code. Here's a simple example:

public class Someclass
{
   public native void thisCallsCMethod(Someparams);
}

      

Now create JNI wrappers:

javac Someclass.java
javah Someclass

      

This will create Someclass.h, then you will create Someclass.cpp and include .h in it. At this point, all you have to do is write C / C ++ code for thiCallsCMethod



In .h you will see the method signature that you must implement. Something like:

#include "clibraryHeader.h"
using namespace clibraryNamespace;

JNIEXPORT void JNICALL thisCallsCMethod(JNIEnv *, someparameters)
{
   cout<<"Yeah C code is being called"<<endl;
   someCfunction();
}

      

Obviously you need to mass the parameters in the JNI call, but you can create some temporary variables and then copy back the values ​​obtained from the C calls into the incoming parameters (if they need to be returned), etc.

May be:

#include "clibraryHeader.h"
using namespace clibraryNamespace;

JNIEXPORT void JNICALL thisCallsCMethod(JNIEnv *, someparameters)
{
   cout<<"Yeah C code is being called"<<endl;
   Cstruct temp;
   temp1.somevar = param1.getSomeVal()
   someCfunction(temp);
}

      

0


source







All Articles