JT.
JT.

Reputation: 381

Call JNI methods that were not written for your class

It seems that JNI methods need to be written with the Java class signature built in to them. I want to call a JNI method that I didn't write. Can I call a native method on a library that was not written with my class in mind?

Upvotes: 2

Views: 230

Answers (1)

L. Cornelius Dol
L. Cornelius Dol

Reputation: 64026

Given:

package com.mycompany.package

class MyClass
{
public native void doSomething();
}

is transformed (mangled) into a natively linked method name of:

Java_com_mycompany_package_MyClass_doSomething

it seems you would need the same class in the same package in order to connect the native method to the Java method. This seems like it's likely to be problematic and/or error prone if you don't have control over the native library. And packaging your code in a foreign package is a bad idea, esp. if the foreign package is signed and sealed.

Also problematic is that native invocation generally have some specific considerations which you might be violating - like thread-safety concerns, or releasing memory or lock (the need to call other native functions around the one you're using).

From my (considerable) experience with JNI I wouldn't recommend it unless you're desperate and have no other options, and you're really familiar with the target system and API.

Your better option would be to write a simple native wrapper around the target O/S API(s) you want to use.

Upvotes: 2

Related Questions