Search code examples
c#javadlljna

How to use C# function in Java using JNA lib


I've spent many hours trying to use a C# function inside my Java Application but had no success... I wrote the following lib in C#:

public class Converter
{

    public Converter()
    {
    }

    public bool ConvertHtmlToPdf(String directoryPath)
    {
        //DO SOMETHING
    }
}

This dll calls another dll to make some operations but when I compile it I can find Dlls in my Realse folder and everything seems to be ok, so I compiled it using 32bit option, 64bit, and Any CPU option just to make sure that it's not my issue.

Analizing my dll files with Dependency Walker in 32 bit and Any CPU option it says that IESHIMS.DLL can't be found, and show this message:

Warning: At least one delay-load dependency module was not found. Warning: At least one module has an unresolved import due to a missing export function in a delay-load dependent module.

It doesn't occur with the 64bit file, nevertheless I can't find my ConvertHtmlToPdf function.

As I don't know if it is relevant or not, my second step was in the Java Code.

To load my library I do:

System.setProperty("jna.library.path", "C:\\Program Files (x86)\\Facilit\\Target App\\lib");

and:

public interface IConversorLibrary extends Library {

    IConversorLibrary INSTANCE = (IConversorLibrary) Native.loadLibrary("converter", IConversorLibrary.class);

    void ConvertHtmlToPdf(String directoryPath);
}

(The lib seems to be load successful, cause if I try to delete dll file with my application running it says that can't be deleted cause it's in using) and finally:

IConversorLibrary.INSTANCE.ConvertHtmlToPdf(directoryPath);

But the result is not really as I wish:

java.lang.UnsatisfiedLinkError: Error looking up function 'ConvertHtmlToPdf': Could not find the specified procedure.

I don't know what I'm doing wrong, I've tried many tutorials and many things, but anything seems to work, any help is really appreciated.


Solution

  • As said by technomage:

    JNA can load from DLLs that use C linkage. A C# class does not by default support any kind of C linkage. C++ supports C linkage with the extern "C" notation.

    This article shows a way to make C# DLLs methods callable like C-style DLL, unfortunately it's a quite complex.