让JNA使用Java => C#?

时间:2011-05-15 15:11:54

标签: c# java jna

我在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接口中?或者我可以省略我不关心的界面?

非常欢迎任何示例代码!

3 个答案:

答案 0 :(得分:11)

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

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

有几种选择:

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

答案 1 :(得分:1)

这款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;
}

<强>爪哇

在顶部添加导入:

   import com.sun.jna.Native;

在班级中添加界面。它的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"));

答案 2 :(得分:0)

您可以将咖啡因用于此http://caffeine.berlios.de/site/documentation/