VC++.NET – The Glue To Integrate .NET and Java

Have you ever had the need for Java/.NET Integration ?
Although the main approach is web services interop, sometimes it’s necessary to do some lower level integration.
For example if you have a neat java library for instance for logging purposes which is tightly integrated in your application.

Why not use it within your .NET application as well ?

With VC++.NET and Java Native Interface (JNI) it’s not that complicated.
Just load the Java VM into the .NET process and call the Java methods with the help of unmanaged C++.

Below you can see an example of how to call the method

boolean MyLogger.log(String name)

which resides in C:\temp\mylogger.jar and is part of the package net.pleus. The class uses log4j.


#include “jni.h” // included in the jdk, link to jvm.lib as well

// configure Java VM
JavaVMOption options[3];
options[0].optionString = “-Djava.compiler=NONE”;
options[1].optionString = “-Djava.class.path=C:\\temp\\mylogger.jar;C:\\temp\\log4j.jar”;
options[2].optionString = “-verbose:jni”;

JavaVMInitArgs vm_args;

vm_args.version = JNI_VERSION_1_4;
vm_args.options = options;
vm_args.nOptions = 3;
vm_args.ignoreUnrecognized = JNI_FALSE;

// load Java VM
JavaVM* jvm;
JNIEnv* env;
JNI_CreateJavaVM(&jvm,(void **)&env, &vm_args);

// find class and method
jclass cls = env->FindClass(“net/pleus/MyLogger”);
jmethodID mid = env->GetStaticMethodID(cls,”log”,”(Ljava/lang/String;)Z”);

// call method
jstring name = env->NewStringUTF(“my message”);
bool res = env->CallStaticObjectMethod(cls,mid,name);

// cleanup
jvm->DestroyJavaVM();

The technology stack could be as follows:

Managed Code (C#, VB.NET) -> Hybrid C++.NET and JNI -> Java

I tried it out. It works very well (and fast).
The most difficult thing is to perform the type conversions and code the cumbersome signature descriptions.
The other way round (call .NET from Java) is also possible though it’s a little bit trickier.

New Article About C++ Templates in VS.NET

The german dotnetpro magazine published my latest article about the new C++ template features in VS.NET.
With the 2003 release C++.NET achieved nearly 100% standards conformance.
This might be interesting news for the virtual machine vendors, because certainly they won’t write their VM’s from scratch for every new operating system. This can be achieved for instance by using ANSI C++.