我在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
接口中?或者我可以省略我不关心的界面?
非常欢迎任何示例代码!
答案 0 :(得分:11)
您将无法直接从Java调用C#代码。 JNA只能访问本机库(C或C ++)。但是,您可以在库中启用COM Interop,并将2与本机包装器链接在一起。即它会看起来像:
Java --(JNA)--> C/C++ --(COM Interop)--> C#
有几种选择:
答案 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)