Reputation: 51
I have one c++ dll file. And I know the methods used in it. I need to call these methods from my java code. I don't have access to modify the DLL file. Please provide me a solution to do this.
Upvotes: 2
Views: 11627
Reputation: 4994
I created JavaCPP exactly for that purpose. I'll copy/paste some sample code and explanations from the page:
The most common use case involves accessing some legacy library written for C++, for example, inside a file named LegacyLibrary.h containing this C++ class:
#include <string>
namespace LegacyLibrary {
class LegacyClass {
public:
const std::string& get_property() { return property; }
void set_property(const std::string& property) { this->property = property; }
std::string property;
};
}
To get the job done with JavaCPP, we can easily define a Java class such as this one--although one could use the Parser to produce it from the header file as demonstrated below:
import com.googlecode.javacpp.*;
import com.googlecode.javacpp.annotation.*;
@Platform(include="LegacyLibrary.h")
@Namespace("LegacyLibrary")
public class LegacyLibrary {
public static class LegacyClass extends Pointer {
static { Loader.load(); }
public LegacyClass() { allocate(); }
private native void allocate();
// to call the getter and setter functions
public native @StdString String get_property(); public native void set_property(String property);
// to access the member variable directly
public native @StdString String property(); public native void property(String property);
}
public static void main(String[] args) {
// Pointer objects allocated in Java get deallocated once they become unreachable,
// but C++ destructors can still be called in a timely fashion with Pointer.deallocate()
LegacyClass l = new LegacyClass();
l.set_property("Hello World!");
System.out.println(l.property());
}
}
Alternately, we can produce a Java interface by parsing the header file with a config class such as this one:
@Properties(target="LegacyLibrary", value=@Platform(include="LegacyLibrary.h"))
public class LegacyLibraryConfig implements Parser.InfoMapper {
public void map(Parser.InfoMap infoMap) {
}
}
And the following build commands:
$ javac -cp javacpp.jar LegacyLibraryConfig.java
$ java -jar javacpp.jar LegacyLibraryConfig
$ javac -cp javacpp.jar LegacyLibrary.java
$ java -jar javacpp.jar LegacyLibrary
For more complex examples including Maven/IDE integration, check out the JavaCPP Presets!
Upvotes: 4