How to use C# function in Java using JNA lib

|▌冷眼眸甩不掉的悲伤 提交于 2019-11-30 21:43:45

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.

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"));
标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!