Search code examples
c#c++dlljava-native-interfaceinclude

Importing a C# DLL into C++ for use with JNI


I am writing a program in Java which must use a DLL file (which is one written in C#), I figured the best way to do this is to write a C++ program as an interface, and then use JNI. The C++ program will be responsible for using the DLL in a JNI friendly way so that I can then call it from my Java program.

I'm trying to include a DLL file in C++ but I am getting the following error on compilation.

warning C4335: Mac file format detected: please convert the source file to either DOS or UNIX format

The way I am including said DLL:

#include "LibraryName.dll"

I am including/using or making any incorrect assumptions about the use of DLLs in this way? How would I fix this error?


Solution

  • You can avoid C++ and make calls from Java to C# and back directly, but you'll have to bootstrap the whole thing from C# side:

    1. In your Java program create a class and expose a JNI method:
    public class Foo {
        static native void bar(); // This method will be implemented in C#
    }
    
    1. Compile the Java program into a JAR file
    2. Write a "bootstrap" program in C# that loads the DLL, starts the JVM in-process with the JAR in classpath, and uses JNI RegisterNatives to provide the callback for bar() method and invoke your DLL accordingly.

    Please see Apache Ignite.NET code as an example of cross-platform .NET/Java interop:

    Feel free to copy and modify this code to your needs, Apache license allows that.

    The whole thing is rather complicated, but it is the most performant approach. The only alternative is to run .NET and Java in separate processes and use pipes or some other mechanism to communicate.