Getting JNA to work with Java => C#?

前端 未结 3 1024
我寻月下人不归
我寻月下人不归 2020-12-20 19:52

I\'ve written a lot of code in a C# library, which I now need to call from Java.

I saw it recommended on SO to use JNA, but I\'m having trouble even getting out of t

相关标签:
3条回答
  • 2020-12-20 20:21

    This Nugget is super easy to use and works perfectly. https://www.nuget.org/packages/UnmanagedExports

    You need Visual Studio 2012 (Express works fine). Once installed, just add [RGiesecke.DllExport.DllExport] before any static function you want to export. That's it!

    Example:

    C#

    [RGiesecke.DllExport.DllExport]
    public static int YourFunction(string data)
    {
         /*Your code here*/
         return 1;
    }
    

    Java

    Add the import at the top:

       import com.sun.jna.Native;
    

    Add the interface in your class. Its your C# function name preceded by the letter "I":

      public interface IYourFunction extends com.sun.jna.Library
        {
           public int YourFunction(String tStr);
        };
    

    Call your DLL where you need it in your class:

    IYourFunction iYourFunction = (IYourFunction )Native.loadLibrary("full or relative path to DLL withouth the .dll extention", IYourFunction.class);//call JNA
            System.out.println("Returned: " + IYourFunction.YourFunction("some parameter"));
    
    0 讨论(0)
  • 2020-12-20 20:33

    You won't be able to call directly into your C# code from Java. JNA will only be able to access a native library (C or C++). However you could enable COM Interop in your library and link the 2 together with a native wrapper. I.e. it would look some thing like:

    Java --(JNA)--> C/C++ --(COM Interop)--> C#

    There are a couple of alternatives:

    • Make the C# a stand alone command line app and have the Java code send/receive data from it using stdin/stdout (ProcessBuilder can help you here).
    • Run the C# as a stand alone app with some form of platform neutral messaging protocol to communicate between the 2 of them, e.g. HTTP, AMQP.
    0 讨论(0)
  • 2020-12-20 20:41

    You can use Caffeine for this http://caffeine.berlios.de/site/documentation/

    0 讨论(0)
提交回复
热议问题