Call C++ function with args from Java.

Hi.

I am working on a project in a group at a university. I really need help with this one.

We are creating a GUI in Java where the user can enter parameters. Then we want to be able to pass these parameters to a function inside our C/C++ program, that does the rest. How do I do this? So far I have managed to call a simple helloworld-function by using JNI, dll and a javah tool that helps me create a header file from a java file. I define the helloworld-function in C and call it from Java.

Java file:
1
2
3
4
5
6
7
8
9
10
11
12
13
package helloworld;

public class HelloWorld {

 private native void print();

 public static void main(String[] args) {
     new HelloWorld().print();
 }

 static {
     System.loadLibrary("HelloWorld");
 }  }


Header file:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
/* DO NOT EDIT THIS FILE - it is machine generated */
#include <jni.h>
/* Header for class HelloWorld */

#ifndef _Included_HelloWorld
#define _Included_HelloWorld
#ifdef __cplusplus
extern "C" {
#endif
/*
 * Class:     HelloWorld
 * Method:    print
 * Signature: ()V
 */
JNIEXPORT void JNICALL Java_HelloWorld_print
  (JNIEnv *, jobject);

#ifdef __cplusplus
}
#endif
#endif


C file:
1
2
3
4
5
6
7
8
9
10
#include "stdafx.h"
#include <jni.h>
#include <stdio.h>
#include "HelloWorld.h"   

JNIEXPORT void JNICALL Java_HelloWorld_print(JNIEnv *env, jobject obj)
{
     printf("Hello World!\n");
     return;
} 


My problem is that I do not know how to call the helloworld-function with parameters. I guess that this is a special case when using JNI and a . dll. How do I pass simple char- and int-arguments from the Java class to the helloworld-C-function?

Thanks for all help.
Best regards, Zerpent.
Last edited on
There is probably a better way... But you could save parameters to a txt file and then read them into the C++ file.
Last edited on
Maybe you could use the jobject that is passed along? If that is the class you are calling it from, you can put the parameters there I guess.
This IBM article includes examples of how to use parameters with JNI, and how to returns various types as well.

Java programming with JNI
http://www.ibm.com/developerworks/java/tutorials/j-jni/section2.html

Andy
Last edited on
Thanks for helping me with this project. I will take a look at that link.
I experimented with JNI, it was fun. There's also JNA which is worth checking out:
https://github.com/twall/jna
Topic archived. No new replies allowed.