Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations gkittelson on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

How do you call a C/C++ function from Java? 1

Status
Not open for further replies.

cpjust

Programmer
Sep 23, 2003
2,132
US
Hi,
I have a C++ DLL, .lib & .h file.
I need to call the C++ functions that are in the DLL from my Java program.

I've heard about JNI and a native keyword in Java, but I haven't been able to find any comprehensive examples...

For simplicity, lets assume I want to call the following WinAPI function:
Code:
LONG RegOpenKeyEx( HKEY  hKey,
                LPCTSTR  lpSubKey,
                  DWORD  ulOptions,
                 REGSAM  samDesired,
                  PHKEY  phkResult );
Header: Declared in Winreg.h; include Windows.h.
Library: Use Advapi32.lib.

What's the easiest way to call this function from a Java program?

I guess the most confusing thing for me is how to represent C++ pointers & references in Java?
In Java, Strings are classes, but in C/C++ they are pointers to arrays of bytes. Also, phkResult is an output parameter passed as a pointer; would that cause any problems?
 
You cannot map Java to existing C/C++ code/functions.

If you need Java to utilise an existing C/C++ API, then
you must use JNI to provide a wrapper around that native functionality.

For example, in "JNI C/C++" a Java String object maps to a C/C++ type of "jstring" - which, in C/C++ can be then converted to a char* .

Read some tutorials. Its actually quite simple - as long as you are not passing odd structures/classes through the calls and keep it all basically primitive data typed).

See :




--------------------------------------------------
Free Java/J2EE Database Connection Pooling Software
 
I wanted to create a Java wrapper around a set of C++ API's, and now I need to create a C++ wrapper around the C++ API's first. Great... :-(
Thanks for the links though. They look like they should help.
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top