How can I call C or C++ code from servlets?

Alexander Krapf

You have two major options, JNI and CORBA. JNI is Java's gateway to languages that can link with C. CORBA is OMG's Common Object Request Broker Architecture. Both are pretty hard to use.

[See the jGuru JNI FAQ and CORBA FAQ for more information on using these technologies. -Alex Chaffee]

JunC++ion is a product that is built on top of JNI and makes the Java/C++ interoperability problem basically a non-issue. JunC++ion generates proxy classes for compiled Java classes, for example for a Servlet class. It also performs the task of the javah compiler but goes one step further: it generates an implementation of the native method that delegates to a C++ method. This allows you for example to implement a native servlet method in C++ like this:

  void _cmj_Java_MyServlet_doHandleGet( jcpp_localenv * _env,
    MyServlet & _this, HttpServletRequest & _req, 
    HttpServletResponse & _resp )
  {
    ServletOutputStream os = _resp.getOutputStream();
    char                buffer[ 512 ];
    os.println( "<!-- from native start -->" );
    try
    {
      sprintf( buffer, "This is a message from %s
", call_cpp_api() );
      os.println( buffer );
    }
    catch(...)
    {
      throw MyException( "something bad happened" );
    }
    os.println( "<!-- from native end -->" );
  }
JunC++ion is currently available on Wintel but is actively being ported to Solaris, AIX, Linux and HP-UX. More information is available at http://www.codemesh.com

[Note that Alexander Krapf, the author of this answer, is the president of CodeMesh. -Alex Chaffee]

Comment and Contribute

 

 

 

 

 


(Maximum characters: 1200). You have 1200 characters left.

 

 

About | Sitemap | Contact