Entry
Can I access the methods in a COM object from Java? If so, could you please show me how?
Jul 24th, 2001 07:24
Kevin Curry, Jake Zajac,
Yes, you CAN access COM objects from Java (call methods on them
anyway), but you'll have to go through JRI (Netscape) or JNI to do it.
I imagine you can only communicate back and forth when using primitive
data types that can be converted. If it's just a one-way call then
that may not be the case.
In my case, I have to call a COM method from Java and return the result
to JavaScript (via LiveConnect). I won't get into all the JRI/JNI
stuff, but basically I had to write a couple of methods that convert
Java Objects to VARIANTs and VARIANTs back into Java Objects. If the
COM object being called also takes parameters that are passed in from
Java, then those params will have to be converted into something like a
SAFEARRAY.
I'm not a COM expert, but I had to do this to invoke a COM XML-RPC
client from a LiveConnect applet and it was not too difficult. Here's
some pseudocode that I hope helps:
void VectorToSAFEARRAY( JRIEnv* env,
struct java_util_Vector* _fromVector, SAFEARRAY* _toARRAY ) {
// The arguments to my xml rpc call are passed in as
// a Java Vector. This method simply checks the JRI_InstanceOf
// to see the data type of each element, converts it to a
// VARIANT, and stores the val in _toARRAY. This is ok b/c all the
// clients in my system agree to pass "primitive" data types (int,
// bool, String, etc.)
// for instance...
java_lang_Class* StringCls =
JRI_FindClass(env, "java/lang/String" );
// we consider the String to be primitive, even if 1 char.
_variant_t val;
// iterate through the Vector and check currItem
if (JRI_IsInstanceOf(env, currItem, StringCls)) {
java_lang_String *jStr = (java_lang_String*)currItem;
_bstr_t jChars( JRI_GetStringUTFChars(env, jStr) );
val = jChars;
}
SafeArrayPutElement(_toARRAY, &i, &val);
}
jref VARIANTtoObject( JRIEnv* env, _variant_t _variant ) {
// switch on (vt & VT_TYPEMASK)
// in each case statement, instantiate the appropriate Java
// data type and copy _variants primitives into it
jref jResult;
switch(vt & VT_TYPEMASK) {
case VT_BSTR:
strVal = _bstr_t(_variant.bstrVal);
jResult = JRI_NewStringUTF( env, strVal, strVal.length() );
break;
}
// caller responsible for memory allocated by JRI_NewStringUTF!
return jResult;
}