C++ wrapper code
Hi.
We want to access an existing dll through java. Since we cannot make any modifications in the dll, we are writing a C++ wrapper class. Problem is - I am absolutely new to C++, so could anyone please direct me to some example code that I can study, to write this C++ wrapper.
Thanks in advance.
Is that a Java or a C++ question? Do you intend to write a wrapper that itself is JNI-compliant so you can call it from within Java? In the latter case, nothing will really force you to write a C++ wrapper class. You can keep the instance and the static state within Java. The native method implementations could even be plain fuctional.
Just for wrapping, there are a whole lot of previous threads. Check out:
http://forum.java.sun.com/thread.jsp?forum=52&thread=95029
http://forum.java.sun.com/thread.jsp?forum=52&thread=94407
Or run search with something like this:
http://search.java.sun.com/Search/java?qt=DLL+wrap+native&nh=10&qp=%2Bforum%3A52&col=javafrm&survey=0&rf=0&st=11
hi,
you are right - this is more of a C++ question. I have posted it on some C++ forums too, but I was hoping someone here would have come across a similar situation.
Basically, i want to know how to call a dll from the C++ wrapper . Some example code would be a great help!
If the function(s) in the dll can be accessed by including header file(s), all you need is just include the header(s) (of course you need to know which header file to include) in your code (ie: user32.dll). Otherwise, you need to find the function(s) address(es), in order to call the function(s) (ie: JNI_CreateJavaVM in jvm.dll).
To find the function address:void* FindFunctionAddress(char* libpath, char* function) {
HINSTANCE hLib = LoadLibrary(libpath);
if (hLib == NULL) {
return NULL;
}
return GetProcAddress(hLib, function);
}
...
...
void func() {
// getting the function pointer ( function address)
void (*ptrFunc)(void);
ptrFunc = FindFunction(dllPath, funcName);
...
...
// to call the function
(*ptrFunc)();
}
From "The JavaTM Native Interface Programmer's Guide and Specification" An example of find the JNI_CreateJavaVM function address.// from the book
void* JNU_FindCreateJavaVM(char* vmlibpath) {
HINSTANCE hVM = LoadLibrary(vmlibpath);
if (hVM == NULL) {
return NULL;
}
return GetProcAddress(hVM, "JNI_CreateJavaVM");
}
// I wrote myself
void main() {
...
...
// you need to know what the function takes as
// params.
jint (*CreateJavaVM)(JavaVM** pvm, void** penv, void* vmargs);
CreateJavaVM = JNU_FindCreateJavaVM("c:\\jdk1.3\\jre\\bin\\client\\jvm.dll");
if (CreateJavaVM == NULL) {
exit(1);
}
res = (*CreateJavaVM)((JavaVM**)&jvm, (void**)&env, (void*)&vm_args);
...
...
}