Calling unmanaged C++ via Java - java

I needed a Java application to call unmanaged C++. I copied MSVCR90.dll manually from Visual Studio 2008 redist path to the vmware's Windows Server Datacenter.
This is the error I get:
A fatal error has been detected by the Java Runtime Environment:
EXCEPTION_ACCESS_VIOLATION (0xc0000005) at pc=0x73b4ae7a, pid=1108, tid=2272
JRE version: 6.0_38-b05
Java VM: Java HotSpot(TM) Client VM (20.13-b02 mixed mode, sharing windows-x86 )
Problematic frame:
C [MSVCR90.dll+0x3ae7a]
An error report file with more information is saved as:
...\hs_err_pid1108.log
If you would like to submit a bug report, please visit:
http://java.sun.com/webapps/bugreport/crash.jsp
The crash happened outside the Java Virtual Machine in native code.
See problematic frame for where to report the bug.
This is the C++ code:
#include "stdafx.h"
#include <stdio.h>
#include "CCCheckString.h"
#include <vector>
#include <String>
using namespace std;
#include "jobHandler.h"
JNIEXPORT jbolean JNICALL Java_CCCheckString_Login
(JNIEnv *env, jobject object, jstring host, jstring UserName, jstring Domain, jstring Password)
{
bool result;
jobHandler *handler = new jobHandler();
const char *hostStr = (env)->GetStringUTFChars(host, NULL);
string hostS(hostStr);
const char *UserNameStr = (env)->GetStringUTFChars(UserName, NULL);
string UserNameS(UserNameStr);
const char *DomainStr = (env)->GetStringUTFChars(Domain, NULL);
string DomainS(DomainStr);
const char *PasswordStr = (env)->GetStringUTFChars(Password, NULL);
string PasswordS(PasswordStr);
//if comment this line everthing is okey
**result = handler->Login(hostS,UserNameS,DomainS,PasswordS);**
(env)->ReleaseStringUTFChars(host, NULL);
(env)->ReleaseStringUTFChars(UserName, NULL);
(env)->ReleaseStringUTFChars(Domain, NULL);
(env)->ReleaseStringUTFChars(Password, NULL);
delete handler;
return result;
}
Below is the processing code in Java:
CCCheckString ccCheckString = new CCCheckString();
result=ccCheckString.Login("xxx", "xxx", "xx", "xxx");
How can i fix the error?

I solved.
Problem is that Login() accepts std::string but we cannot send it
We reorganize our Login() and it must take const char []
Ex:
bool ClassName::Login(std::string host,std::string userName,std::string userDomain,std::string userPassword)
{ //Orginal Code Here ....}
bool ClassName::Login(const char host[],const char userName[],const char userDomain[],const char userPassword[])
{
std::string strHost(host);
std::string strUserName(userName);
std::string strUserDomain(userDomain);
std::string strUserPassword(userPassword);
return Login(strHost,strUserName,strUserDomain,strUserPassword);
}
Everything is fine.

Related

Error while generating .dll files in Visual Studio 2022. Login authentication using ADSI Api in C++

I want to make a login authentication to my web application(Java). Username and password are created in windows server 2016 active directory. Using that username and password I have to login to my web app using ADSI(Active Directory Service Interface) API in C++ language to connect to the windows server. To do this I have to create the .dll file from the C++ code in Visual Studio 2022. Here I have to add Activeds.lib, adsiid.lib to make the API work. After generating the .dll file to load this in Java System.load() using JNI Concept.
This is the C++ code I used in Visual Studio 2022...
#include <iostream>
#include <jni.h>
#include<string.h>
#include "com_library_ldap_JNIHelper.h"
#include <Iads.h>
#include <adshlp.h>
#include "activeds.h"
#include <windows.h>
#include <stdlib.h>
using namespace std;
JNIEXPORT jstring JNICALL Java_com_library_ldap_JNIHelper_authenticateUser
(JNIEnv* env, jclass, jstring uname, jstring pwd) {
const char* uName = env->GetStringUTFChars(uname, NULL);
std::string username = std::string(uName);
const char* pwd1 = env->GetStringUTFChars(pwd, NULL);
std::string password = std::string(pwd1);
env->ReleaseStringUTFChars(uname, uName);
env->ReleaseStringUTFChars(pwd, pwd1);
IADs* pObject;
wchar_t wname[20];
mbstowcs(wname, username.c_str(), username.length());
LPWSTR szUsername = wname;
wchar_t wpwd[20];
mbstowcs(wpwd, password.c_str(), password.length());
LPWSTR szPassword = wpwd;
HRESULT hr;
string uAdmin = "Admin";
string uUser = "User";
string uType;
bool res = false;
if (uAdmin == "Admin") {
hr = ADsOpenObject(L"LDAP://test.local/CN=Users,DC=test,DC=local",
szUsername,
szPassword,
ADS_SECURE_AUTHENTICATION,
IID_IADs,
(void**)&pObject);
if (SUCCEEDED(hr))
{
// Use the object.
res = true;
// Release the object.
pObject->Release();
}
if (res == true) {
uType = "Admin";
//return env->NewStringUTF(uType.c_str());
}
else
uType = "NotFound!!!";
}
else if (uUser == "User") {
hr = ADsOpenObject(L"LDAP://test.local /CN=Vimaluser,OU=Users,OU=Vimal,DC=test,DC=local",
szUsername,
szPassword,
ADS_SECURE_AUTHENTICATION,
IID_IADs,
(void**)&pObject);
if (SUCCEEDED(hr))
{
// Use the object.
res = true;
// Release the object.
pObject->Release();
}
if (res == true) {
uType = "User";
}
else {
uType = "NotFound!!!";
}
}
return env->NewStringUTF(uType.c_str());
}
below is the error I'm getting...
Build started...
1>------ Build started: Project: Adsi-JNI, Configuration: Release x64 ------
1>Adsi-JNI.cpp
1> Creating library C:\Users\Vimal\Desktop\VS Code\Adsi-JNI\x64\Release\Adsi-JNI.lib and object C:\Users\Vimal\Desktop\VS Code\Adsi-JNI\x64\Release\Adsi-JNI.exp
1>Adsi-JNI.obj : error LNK2019: unresolved external symbol ADsOpenObject referenced in function Java_com_library_ldap_JNIHelper_authenticateUser
1>Adsi-JNI.obj : error LNK2001: unresolved external symbol IID_IADs
1>E:\Java Program\Library System\src\main\java\com\library\ldap\lib\ActiveDS.lib : warning LNK4272: library machine type 'x86' conflicts with target machine type 'x64'
1>E:\Java Program\Library System\src\main\java\com\library\ldap\lib\adsiid.lib : warning LNK4272: library machine type 'x86' conflicts with target machine type 'x64'
1>C:\Users\Vimal\Desktop\VS Code\Adsi-JNI\x64\Release\Adsi-JNI.dll : fatal error LNK1120: 2 unresolved externals
1>Done building project "Adsi-JNI.vcxproj" -- FAILED.
========== Build: 0 succeeded, 1 failed, 0 up-to-date, 0 skipped ==========
And I wrote a code for server connection, but i don't know whether the code is correct for server connection or not. Please help me to solve this problem and also share what are all the things related to this. Thanks in advance.

C + JNI Fails to execute a very simple program

I'll start with my code:
#include <jni.h>
int main(int argc, char const *argv[]) {
JavaVMInitArgs args;
JNIEnv *env;
JavaVM *vm;
args.version = JNI_VERSION_1_8;
args.ignoreUnrecognized = JNI_FALSE;
JNI_CreateJavaVM(&vm, (void **)&env, &args);
jclass System;
jclass PrintStream;
jobject out;
jfieldID outID;
jstring someText;
jmethodID println;
someText = (*env)->NewStringUTF(env, "Hello World");
System = (*env)->FindClass(env, "java/lang/System");
PrintStream = (*env)->FindClass(env, "java/io/PrintStream");
outID = (*env)->GetStaticFieldID(env, System, "out", "Ljava/io/PrintStream;");
out = (*env)->GetStaticObjectField(env, System, outID);
println = (*env)->GetMethodID(env, PrintStream, "println", "(Ljava/lang/String;)V");
(*env)->CallVoidMethod(env, out, println, someText);
return 0;
}
I would expect it to print "Hello World" but it does not, instead I get Segmentation fault (core dumped) annoying error. I could not figure out what is wrong with this code, I tried to comment out everything after someText = (*env)->NewStringUTF(env, "Hello World"); and the program didn't crash, I also tried to comment only the someText = (*env)->NewStringUTF(env, "Hello World"); and I worked too. I even changed the println signature to "boolean" and passed 0 to it, program printed "false" as I would expect so I guess this is something wrong with NewStringUTF method.
openjdk version "1.8.0_131"
OpenJDK Runtime Environment (build 1.8.0_131-b11)
OpenJDK 64-Bit Server VM (build 25.131-b11, mixed mode)
(gdb) bt
#0 0x00007ffff713b2ff in ?? () from /usr/lib/jvm/java-8-openjdk/jre/lib/amd64/server/libjvm.so
#1 0x00007ffff78955c4 in ?? () from /usr/lib/jvm/java-8-openjdk/jre/lib/amd64/server/libjvm.so
#2 0x00007ffff7507e71 in JNI_CreateJavaVM () from /usr/lib/jvm/java-8-openjdk/jre/lib/amd64/server/libjvm.so
#3 0x0000000000400558 in main (argc=1, argv=0x7fffffffe678) at main.c:11
(gdb) info f
Stack level 0, frame at 0x7fffffffe310:
rip = 0x7ffff713b2ff; saved rip = 0x7ffff78955c4
called by frame at 0x7fffffffe490
Arglist at 0x7fffffffe2c8, args:
Locals at 0x7fffffffe2c8, Previous frame's sp is 0x7fffffffe310
Saved registers:
rbx at 0x7fffffffe2d8, rbp at 0x7fffffffe300, r12 at 0x7fffffffe2e0, r13 at 0x7fffffffe2e8, r14 at 0x7fffffffe2f0,
r15 at 0x7fffffffe2f8, rip at 0x7fffffffe308
after commenting out the NewStringUTF
(gdb) bt
#0 0x00007fffe61082b4 in ?? ()
#1 0x0000000000000246 in ?? ()
#2 0x00007fffe6108160 in ?? ()
#3 0x00007fffffffe0f0 in ?? ()
#4 0x00007fffffffe090 in ?? ()
#5 0x00007ffff78f6748 in ?? () from /usr/lib/jvm/java-8-openjdk/jre/lib/amd64/server/libjvm.so
Backtrace stopped: previous frame inner to this frame (corrupt stack?)
(gdb) info f
Stack level 0, frame at 0x7fffffffde80:
rip = 0x7fffe61082b4; saved rip = 0x246
called by frame at 0x7fffffffde88
Arglist at 0x7fffffffde70, args:
Locals at 0x7fffffffde70, Previous frame's sp is 0x7fffffffde80
Saved registers:
rip at 0x7fffffffde78
After some observations, looks like the function JNI_CreateJavaVM is crashing after NewStringUTF was added, but it's "working" after it's removed. How weird is that?
This is JDK and JRE I am using: https://www.archlinux.org/packages/extra/x86_64/jdk8-openjdk/
I am compiling with this command:
gcc \
-I /usr/lib/jvm/java-8-openjdk/include/ \
-I /usr/lib/jvm/java-8-openjdk/include/linux/ \
-L /usr/lib/jvm/java-8-openjdk/jre/lib/amd64/server/ \
-l jvm \
main.c
And running the file with
export LD_LIBRARY_PATH=/usr/lib/jvm/java-8-openjdk/jre/lib/amd64/server/
./a.out
Next Day
Different code, same problem:
#include <jni.h>
#include <stdio.h>
#include <stdlib.h>
int main(int argc, char const *argv[]) {
JavaVMInitArgs args;
JavaVM *jvm;
JNIEnv *env;
args.version = JNI_VERSION_1_8;
args.ignoreUnrecognized = JNI_FALSE;
printf("%s\n", "Creating VM");
JNI_CreateJavaVM(&jvm, (void **)&env, &args);
printf("%s\n", "VM Was Created");
jclass String = (*env)->FindClass(env, "java/lang/String");
if (String == NULL) {
printf("%s\n", "String was NULL");
exit(1);
}
jmethodID method = (*env)->GetMethodID(env, String, "codePointAt", "(I)I");
if (method == NULL) {
printf("%s\n", "method was NULL");
exit(1);
}
printf("%s\n", "I am finishing here");
(*jvm)->DestroyJavaVM(jvm);
return 0;
}
Compile and run:
$ gcc \
> -I /usr/lib/jvm/java-8-openjdk/include/ \
> -I /usr/lib/jvm/java-8-openjdk/include/linux/ \
> -L /usr/lib/jvm/java-8-openjdk/jre/lib/amd64/server/ \
> -l jvm \
> main.c && ./a.out
Creating VM
Segmentation fault (core dumped)
But if I comment the part of the code:
#include <jni.h>
#include <stdio.h>
#include <stdlib.h>
int main(int argc, char const *argv[]) {
JavaVMInitArgs args;
JavaVM *jvm;
JNIEnv *env;
args.version = JNI_VERSION_1_8;
args.ignoreUnrecognized = JNI_FALSE;
printf("%s\n", "Creating VM");
JNI_CreateJavaVM(&jvm, (void **)&env, &args);
printf("%s\n", "VM Was Created");
jclass String = (*env)->FindClass(env, "java/lang/String");
if (String == NULL) {
printf("%s\n", "String was NULL");
exit(1);
}
/*jmethodID method = (*env)->GetMethodID(env, String, "codePointAt", "(I)I");
if (method == NULL) {
printf("%s\n", "method was NULL");
exit(1);
}*/
printf("%s\n", "I am finishing here");
(*jvm)->DestroyJavaVM(jvm);
return 0;
}
Compile and run:
$ gcc \
> -I /usr/lib/jvm/java-8-openjdk/include/ \
> -I /usr/lib/jvm/java-8-openjdk/include/linux/ \
> -L /usr/lib/jvm/java-8-openjdk/jre/lib/amd64/server/ \
> -l jvm \
> main.c && ./a.out
Creating VM
VM Was Created
I am finishing here
So, for me, it works as expected:
> gdb ./main
...
(gdb) run
Starting program: ..../issue/main
[New Thread 0x1403 of process 2600]
[New Thread 0x1503 of process 2600]
warning: unhandled dyld version (15)
Hello World
[Inferior 1 (process 2600) exited normally]
(gdb)
However, I have slightly different env. macOS and I use Oracle's JDK.
Maybe you can try installing debug info and check what exactly happens inside JDK?

How to call C# function from java [duplicate]

This question already has answers here:
Calling C# method within a Java program
(2 answers)
Closed 7 years ago.
I need to call C# function from java and to this I have created the following.
I have a create a java header file Authenticator.h , here is the code:
#include <jni.h>
/* Header for class Authenticator */
#ifndef _Included_Authenticator
#define _Included_Authenticator
#ifdef __cplusplus
extern "C" {
#endif
/*
* Class: Authenticator
* Method: authenticate
* Signature: (Ljava/lang/String;Ljava/lang/String;)Z
*/
JNIEXPORT jboolean JNICALL Java_Authenticator_authenticate
(JNIEnv *, jobject, jstring, jstring);
#ifdef __cplusplus
}
#endif
#endif
I have then create a C# function that Authenticate
namespace SharpAuthenticator
{
public class Authenticator
{
public bool Authenticate(String username,String password)
{
return username == "user" && password == "login";
}
}
}
Then I am trying to call the C# function from C++(project to create a dll) using the code below;
String^ toString(const char *str)
{
int len = (int)strlen(str);
array<unsigned char>^ a = gcnew array<unsigned char>(len);
int i = 0;
while (i < len)
{
a[i] = str[i];
i++;
}
return Encoding::UTF8->GetString(a);
}
bool authenticate(const char *username, const char *password)
{
SharpAuthenticator::Authenticator::Authenticate(toString(username), toString(password));
}
JNIEXPORT jboolean JNICALL Java_Authenticator_authenticate
(JNIEnv *env, jobject c, jstring name, jstring pass)
{
jboolean result;
jboolean isCopyUsername;
const char * username = env->GetStringUTFChars(name, &isCopyUsername);
jboolean isCopypassword;
const char * password = env->GetStringUTFChars(pass, &isCopypassword);
result = authenticate(username, password);
env->ReleaseStringUTFChars(name, username);
env->ReleaseStringUTFChars(pass, password);
return result;
}
And finnally create a dll that i need to call from java. The dll is created and I load it well in java but I get this error log in java. What could I be Missing.
#
# A fatal error has been detected by the Java Runtime Environment:
#
# Internal Error (0xe0434352), pid=9708, tid=7756
#
# JRE version: 7.0-b147
# Java VM: Java HotSpot(TM) Client VM (21.0-b17 mixed mode, sharing windows-x86 )
# Problematic frame:
# C [KERNELBASE.dll+0x812f]
#
# Failed to write core dump. Minidumps are not enabled by default on client versions of Windows
First of all lets create a C# file like this:
using System;
public class Test{
public Test(){}
public String ping(){
return "C# is here.";
}
}
Then compile this with command below:
csc.exe /target:module Test.cs
You can find csc.exe in install path of .NET framework. After that create java file:
public class Test{
public native String ping();
public static void main(String[] args){
System.load("/path/to/dll");
System.out.println("Java is running.");
Test t = new Test();
System.out.println("Trying to catch C# " + r.ping());
}
}
javac Test.java This generates a Test.class.
javah -jni Test This generates a Test.h file which will be included in
C++ code.
After that we need to create our C++ file:
#include "stdafx.h"
#include "JAVA/Test.h"
#include "MCPP/Test.h"
#pragma once
#using <mscorlib.dll>
#using "Test.netmodule"
JNIEXPORT jstring JNICALL Java_Test_ping(JNIEnv *env, jobject obj){
Test^ t = gcnew Test();
String^ ping = t->ping();
char* str = static_cast<char*>((System::Runtime::InteropServices::Marshal::StringToHGlobalAnsi(ping)).ToPointer());
char cap[128];
strcpy_s(cap, str);
return env->NewStringUTF(cap);
}
Finally:
c:\>java Test
I hope this helps you. A basic example to use function C# in Java.
Sources:
https://www.quora.com/How-common-is-the-problem-of-calling-C-methods-from-Java-Do-many-developers-come-across-such-necessity

Fatal error when using jni

I'm trying to use jni to call java methods from c++. actually more of a callback (java -> c++ -> java)
I've checked the c++ program for errors by testing it in .exe (c++ -> java)
The program works perfect in visual studio. but fails and crashes when I convert it to dll and use it in java.
I think it's related to jvm.dll because I had to include it to my visual studio project.
c++:
#include <stdio.h>
#include <jni.h>
#include <string.h>
#include "Inter.h"
JNIEnv* create_vm(JavaVM ** jvm) {
JNIEnv *env;
JavaVMInitArgs vm_args;
JavaVMOption options;
options.optionString = "-Djava.class.path=C:\\Users\\SolidSnake\\workspace\\Test\\bin"; //Path to the java source code
vm_args.version = JNI_VERSION_1_8;
vm_args.nOptions = 1;
vm_args.options = &options;
vm_args.ignoreUnrecognized = 0;
int ret = JNI_CreateJavaVM(jvm, (void**)&env, &vm_args);
if(ret < 0)
printf("\nUnable to Launch JVM\n");
return env;
}
void callMethod() {
JNIEnv *env;
JavaVM * jvm;
env = create_vm(&jvm);
jclass m;
jmethodID test;
m = env->FindClass("Main");
test = env->GetStaticMethodID(m,"callbackFromC","()V");
env->CallStaticVoidMethod(m,test);
}
java:
public final class Main {
public native int callToC();
public static void callbackFromC() {
System.out.println("Hello from C!");
}
public static void main(String[] args) {
System.loadLibrary("Test");
new Main().callToC();
}
}
crash:
#
# A fatal error has been detected by the Java Runtime Environment:
#
# EXCEPTION_ACCESS_VIOLATION (0xc0000005) at pc=0x000007f9aed32ff8, pid=4016, tid=8228
#
# JRE version: Java(TM) SE Runtime Environment (8.0_11-b12) (build 1.8.0_11-b12)
# Java VM: Java HotSpot(TM) 64-Bit Server VM (25.11-b03 mixed mode windows-amd64 compressed oops)
# Problematic frame:
# C [Test.dll+0x1a08] JNIEnv_::FindClass+0x28
#
# Failed to write core dump. Minidumps are not enabled by default on client versions of Windows
Here's how the program goes (j:callToC) -> (c:callMethod) -> (j:callbackFromC)
I had the same problem a couple of days ago and I have found a solution (maybe not the best one) of the problem and now I proud to share it (this one probably would be useful for somebody in the future).
Here is my code that worked well when I had only two projects (C++->Java), that is, the C++-project invoking Java-methods:
void JVM:: Init( const std:: string& javaClassesPath ) {
std:: string optionString = ( std:: string("-Djava.class.path=") + javaClassesPath );
JavaVMOption options_;
options_.optionString = const_cast<char*>( optionString.c_str() );
// initializing of JVM initial arguments:
JavaVMInitArgs arguments_;
memset( &arguments_, 0, sizeof( arguments_ ) );
arguments_.version = JNI_VERSION_1_6;
arguments_.nOptions = 1;
arguments_.options = &options_;
arguments_.ignoreUnrecognized = 0;
// creating JVM:
long status = JNI_CreateJavaVM( &jvm_, (void**)&env_, &arguments_ );
if ( status == JNI_ERR )
throw std:: exception("Error: unable to create Java Virtual Machine.\n");
FindClass("ChartBuilder");
}
This code was being invoked the following way:
JVM JChartBuilder( "D:\\Java Src\\Chart\\Chart.jar" ); // the path that will be used as classpath when creating VM (unless this path is specified it will be unable to find the class ChartBuilder)
Then (Java->C++Java)
When I got the third project (Java) that must invoke methods from that C++-project using JNI, I faced the problem that I cannot create VM when one has already run in the current process. But we can attach to existing VM! So, the code listed above can be changed to suit this requirements:
void JVM:: Init( const std:: string& javaClassesPath )
{
// initializing of JVM options:
std:: string optionString = ( std:: string("-Djava.class.path=") + javaClassesPath );
JavaVMOption options_;
options_.optionString = const_cast<char*>( optionString.c_str() );
// initializing of JVM initial arguments:
JavaVMInitArgs arguments_;
memset( &arguments_, 0, sizeof( arguments_ ) );
arguments_.version = JNI_VERSION_1_6;
arguments_.nOptions = 1;
arguments_.options = &options_;
arguments_.ignoreUnrecognized = 0;
// creating JVM or attaching to JVM:
long status;
/* is there any running VMs in the process? */
JavaVM* createdVMs[1] = { nullptr };
jsize numberOfVMs;
status = JNI_GetCreatedJavaVMs(createdVMs, 1, &numberOfVMs);
/* END OF is there any running VMs in the process? */
if( numberOfVMs != 0 )
{ // if VM already runs:
jvm_ = createdVMs[0]; // get the VM
jvm_->AttachCurrentThread((void**)&env_, NULL); // attach to the VM
}
else
{ // if VM does not run:
status = JNI_CreateJavaVM( &jvm_, (void**)&env_, &arguments_ );
}
if ( status == JNI_ERR )
throw std:: exception("Error: unable to create Java Virtual Machine.\n");
FindClass("ChartBuilder");
}
But that's not all yet. When running main Java-project (the first in Java->C++->Java), I got the following problem: unable to find specified class ChartBuilder. That is I attached to existing VM, but this virtual machine does not know about the path to this class. Remember, that when I created VM in C++, I specified the path explicitly. To solve this problem I have now to specify the classpath additionaly when running main Java-project.
That is all. The only thing I don't like is the need to specify the classpath to ChartBuilder when running main Java-project, but this one is not critical for me, though I'd like to find out how to avoid this need. Maybe somebody knows?

Loading dynamic libraries using JNI and C++ with linux

Recently I'm learning JNI to execute C code. Of course I did basic examples that were on the web. Now Im trying to load a C library that makes dynamic library loading (dlopen). But Im fighthing with an error. Im posting my Java code, C ++ code and the error.
My Java Class
/**
*
* #author glassfish
*/
public class MediationJniWeb {
public String library ;
static {
System.loadLibrary("-core-web");
}
/**
*
* #param library name of mediation core library [32]
* #param method name of method to be executed [128]
* #param parameters parameters of method [10240]
* [partype1,value1,...,valuen]...[partypen,value1,..,valuen]
* #return
*/
private native String execute();
public static void main(String args[]) {
//new MediationJniWeb().callToFunction(null, null, null) ;
MediationJniWeb jniWeb = new MediationJniWeb();
jniWeb.library = "libtest.so" ;
System.out.println(jniWeb.execute());
}
}
I generate .class file with
javac MediationJniWeb
and I generate .h File with
javah -jni MediationJniWeb
my MediationJniWeb.h file is
/* DO NOT EDIT THIS FILE - it is machine generated */
#include <jni.h>
/* Header for class MediationJniWeb */
#ifndef _Included_MediationJniWeb
#define _Included_MediationJniWeb
#ifdef __cplusplus
extern "C" {
#endif
/*
* Class: MediationJniWeb
* Method: execute
* Signature: ()Ljava/lang/String;
*/
JNIEXPORT jstring JNICALL Java_MediationJniWeb_execute
(JNIEnv *, jobject);
#ifdef __cplusplus
}
#endif
#endif
and my MediationJniWEb.cpp file
/* DO NOT EDIT THIS FILE - it is machine generated */
#include <jni.h>
#include <dlfcn.h>
#include <iostream>
#include "MediationJniWeb.h"
using namespace std ;
typedef void (*test)(string);
/*
* Class: MediationJniWeb
* Method: execute
* Signature: ()Ljava/lang/String;
*/
JNIEXPORT jstring JNICALL Java_MediationJniWeb_execute
(JNIEnv * env, jobject obj){
const char * str_library ;
jfieldID fid_library ;
jstring jstr_library ;
jboolean isCopy ;
jclass cls = env->GetObjectClass( obj) ;
fid_library = env->GetFieldID( cls,"library", "Ljava/lang/String;");
jstr_library = ( jstring )env->GetObjectField( obj,fid_library);
str_library = env->GetStringUTFChars( jstr_library, &isCopy) ;
void* handle = dlopen(str_library, RTLD_NOW); // open libtest.so
if ( 0 == handle ) {
cout << "failed to load 'libtest.so'. " << dlerror () <<endl;
exit(1);
}
test t = (test)dlsym(handle, "_Z8testfuncSs"); // run default method
if ( 0 == t ) {
cout << "failed to load 'testfunc()'." << endl;
exit(1);
}
t("Hello, World!");
dlclose(handle);
/*
*/
return env->NewStringUTF( str_library); // I just return library name just for fun
}
}
I compile with
g++ -shared -fpic -I//include/ -I//include/linux/ MediationJniWeb.cpp -o lib-core-web.so MediationJniWeb.cpp -ldl
this generate lib-core-web.so file. Then I copy this to $HOME/lib and I configure
LD_LIBRARY_PATH=$HOME/lib
Now I create my library libtest.so that is going to be executed by lib-core-web.so
I create file for shared libray mylib.cpp
#include <iostream>
#include <string>
using namespace std;
void testfunc(string s)
{
cout << s << endl;
}
I compile this that is going to work as a shared library with
g++ -shared -fpic -o libtest.so mylib.cpp
This command generates libtest.so file.. and also, I copy it to $HOME/lib
That's all I do to call from JNI to a C++ library to load a dynamic library.
when I execute MediationJniWeb java class I'm having this error
failed to load. libtest.so: cannot open shared object file: No such
file or directory
What do I have to do with libtest.so ?? where do I have to put it ?
I have on mind that configuring only LD_LIBRARY_PATH variable with right path, JVM should know where to find all needed libraries to be loaded.
Please help with your comments and let me know where my mistakes are.
Thanks in advance !
A simple thing I have done
instead of
jniWeb.library = "libtest.so"
library parameter to be loaded I declared
jniWeb.library = "/home/myuser/lib/libtest.so"
And it worked !

Categories