How to use C# function in Java using JNA lib

后端 未结 2 1969
故里飘歌
故里飘歌 2020-12-18 03:57

I\'ve spent many hours trying to use a C# function inside my Java Application but had no success... I wrote the following lib in C#:

public class Converter
{         


        
相关标签:
2条回答
  • 2020-12-18 04:49

    As said by technomage:

    JNA can load from DLLs that use C linkage. A C# class does not by default support any kind of C linkage. C++ supports C linkage with the extern "C" notation.

    This article shows a way to make C# DLLs methods callable like C-style DLL, unfortunately it's a quite complex.

    0 讨论(0)
  • 2020-12-18 04:53

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

    You need Visual Studio 2012 (express). 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)
提交回复
热议问题