How to call into .NET dll from Java

37,851

Solution 1

Check the http://www.javonet.com as well. With one-jar file you can load this dll and call as follows:

Javonet.AddReference("your-lib.dll");
int result = Javonet.getType("ReturnINT").Invoke("RetornaInteiro");

Javonet will automatically load your library in .NET process and give you access to any classes and types contain within it. Next you can get your type and invoke static method. Method results and arguments are automatically translated between JAVA and .NET types. You can pass for example string or bool arguments like that

Boolean arg1 = true;
String arg2 = "test";
Javonet.getType("ReturnINT").Invoke("MethodWithArguments",arg1,arg2);

And they will be translated automatically.

In addition you can also create instance of your type, subscribe events, set/get properties and fields, handle exceptions or even pass value-type arguments. Check the docs for more details:

http://www.javonet.com/quick-start-guide/

PS: I am member of Javonet team. Therefore feel free to ask me any detailed questions regarding native integrations and our product.

Solution 2

You can call it directly: http://jni4net.sourceforge.net/

Or you can call it as an executable.

Share:
37,851
soamazing
Author by

soamazing

Updated on April 09, 2020

Comments

  • soamazing
    soamazing about 4 years

    I have this code to create a simple .NET .dll. It only returns an int.

    But, it is not working inside Java.

    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Text;
    
    namespace ReturnINT
    {
        public class ReturnINT
        {
    
            public static int RetornaInteiro ()
            {
                try
                {
                    int number = 2;
    
                    return number;
                }
                catch (Exception)
                {
                    return 1;
                }
            }
        }
    }
    

    How can I call the method from within Java?

    When I Use JNI i have this error IN java:

    Exception in thread "main" java.lang.UnsatisfiedLinkError: Dll.RetornaInteiro()V
          at Dll.RetornaInteiro(Native Method)
          at Dll.main(Dll.java:27)