I've written a lot of code in a C# library, which I now need to call from Java.
I saw it recommended on SO to use JNA, but I'm having trouble even getting out of the starting blocks; the documentation there is very sketchy.
Firstly, it only appears to show you how to connect to the Native C library, which is no good to me; I want to connect to my own library. The code sample there shows:
// 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);
}
I want to connect to my library (MyLibrary.dll), and call a static method on MyNamespace.MyClass
whose C# signature is:
public static string HelloWorld(string p)
So what parameters to I give to Native.loadLibrary()
?
That's just for "Hello World". What if I want to return an object? Let's say MyClass
also has a static method
public static MyClass GetInstance()
How would I call that using JNA? I guess I would have to define an interface in Java that matches the C# MyClass
interface... but would it have to be exhaustive, i.e. for every public member of MyClass
I would have to declare a method in an IMyClass
interface in Java? Or can I just leave out the interfaces I don't care about?
Any sample code would be gratefully welcomed!
You won't be able to call directly into your C# code from Java. JNA will only be able to access a native library (C or C++). However you could enable COM Interop in your library and link the 2 together with a native wrapper. I.e. it would look some thing like:
Java --(JNA)--> C/C++ --(COM Interop)--> C#
There are a couple of alternatives:
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With