Java using .DLL library

5

I'm having trouble creating the interface in java, because I can not figure out the header of the function in C.

Example Header C function:

CMOEP_API char * CALLCONV CMP_GetLastError( );

Now in java I have this but I do not know how to implement the methods:

public class DllFIles {


    public static void main(String[] args) {
     CMOEP lib = new CMOEP();
        System.out.println("ERRO: " +lib.CMP_GetLastError());

    }

}
class CMOEP{
    static {
        System.loadLibrary("CMOEP");
    }
    public native char[] CMP_GetLastError( );
    //    CMOEP_API char * CALLCONV CMP_GetLastError( );

    public CMOEP(){}
}

Any ideas / help?

    
asked by anonymous 22.09.2014 / 17:07

1 answer

3

You can use this Github project to make your life easier: link

Walkthrough:

  • Create a Maven Project
  • Create source C
  • Create the Java interface
  • Create the Java class
  • Sources:

    dependency on pom.xml

        <dependency>
            <groupId>net.java.dev.jna</groupId>
            <artifactId>jna</artifactId>
            <version>4.1.0</version>
        </dependency>
    

    Code C

    #include <stdio.h>
    
    int soma(int num1, int num2){
      int resultado = num1 + num2;
      return resultado;
    }
    

    Java interface

    package jna;
    
    import com.sun.jna.Library;
    
    public interface SomaJNA extends Library {
      public int soma(int num1, int num2);
    }
    

    Java class

    package jna;
    
    import com.sun.jna.Native;
    
    public class FazSoma {
        public static void main(String[] args) {
            SomaJNA calculadora = (SomaJNA) Native.loadLibrary("somadorJNA",
                    SomaJNA.class);
    
            int num1 = Integer.parseInt(args[0]);
            int num2 = Integer.parseInt(args[1]);
    
            int resultado = calculadora.soma(num1, num2);
            System.out.println("A soma é: " + resultado);
        }
    }
    

    How to get in the Eclipse Project

    That's All!

        
    14.10.2014 / 23:45