让JNA使用Java => C#?

我在C#库中编写了很多代码,我现在需要从Java调用它。

我在SO上建议使用JNA ,但是我甚至无法摆脱起跑线; 那里的文件非常粗略。

首先,它似乎只是告诉你如何连接到Native C库,这对我没有好处; 我想连接到我自己的库。 代码示例显示:

// This is the standard, stable way of mapping, which supports extensive // customization and mapping of Java to native types. public interface CLibrary extends Library { CLibrary INSTANCE = (CLibrary) Native.loadLibrary((Platform.isWindows() ? "msvcrt" : "c"), CLibrary.class); void printf(String format, Object... args); } 

我想连接到我的库(MyLibrary.dll),并在MyNamespace.MyClass上调用一个静态方法,其C#签名是:

 public static string HelloWorld(string p) 

那么我给Native.loadLibrary()参数是什么?

这只是为了“Hello World”。 如果我想要返回一个对象怎么办? 假设MyClass也有一个静态方法

 public static MyClass GetInstance() 

我怎么称呼使用JNA? 我想我必须在Java中定义一个与C# MyClass接口匹配的接口……但是它必须是详尽的,即对于MyClass每个公共成员,我必须在Java中的IMyClass接口中声明一个方法吗? 或者我可以省略我不关心的界面?

欢迎任何示例代码!

您将无法直接从Java调用C#代码。 JNA只能访问本机库(C或C ++)。 但是,您可以在库中启用COM Interop,并将2与本机包装器链接在一起。 即它会看起来像:

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

有几种选择:

  • 使C#成为一个独立的命令行应用程序,让Java代码使用stdin / stdout从它发送/接收数据( ProcessBuilder可以在这里帮助你)。
  • 使用某种forms的平台中立消息传递协议将C#作为独立应用程序运行,以在它们中的两个之间进行通信,例如HTTP,AMQP。

这款Nugget非常易于使用,效果很好。 https://www.nuget.org/packages/UnmanagedExports

您需要Visual Studio 2012(Express工作正常)。 安装后,只需在要导出的任何静态函数之前添加[RGiesecke.DllExport.DllExport] 。 而已!

例:

C#

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

Java的

在顶部添加导入:

  import com.sun.jna.Native; 

在您的class级中添加界面。 它的C#函数名称前面带有字母“I”:

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

在课堂上调用您需要的DLL:

 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")); 

你可以使用咖啡因来http://caffeine.berlios.de/site/documentation/