3

I have one c++ dll which is previously used for c# application. now we want to use the same dll for java . i know that we can use JNI technology for this but the problem we have to use the same method signature we don't want to change the method singnature. please advise me.

jww
  • 97,681
  • 90
  • 411
  • 885
Madhu
  • 51
  • 2
  • 5
  • Are you sure your library uses standard C++? C# cannot access C++ classes unless they are wrapped with C++/CLI. – Samuel Audet Oct 15 '14 at 03:42
  • 4
    I believe this question is not duplicate. The **[9485896](http://stackoverflow.com/questions/9485896/calling-c-dll-from-java)** asks how to create a C++ DLL to work with Java, and the accepted answer relates to this problem. This question is about a minimal wrapper that would allow access to existing methods from Java. – Alex Cohn Oct 15 '14 at 09:28

2 Answers2

3

One option is using JNA instead of JNI. It eliminates the need for the boilerplate native 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));
  }
}
Jason
  • 3,777
  • 14
  • 27
-2

You don't have to change the method signature, you simply add a native method which then calls the native C++ code. Here is a simple example:

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

Now create the JNI wrappers:

javac Someclass.java
javah Someclass

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

In the .h you'll see a method signature that you have to implement. Something along the lines of:

#include "clibraryHeader.h"
using namespace clibraryNamespace;

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

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

Maybe:

#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);
}
ventsyv
  • 3,316
  • 3
  • 27
  • 49
  • This answer does not answer the question how to call an existing DLL, which can/should not be modified. – Datz Sep 24 '19 at 05:41