简体   繁体   中英

How to call a function with arguments in C++ from JAVA using JNI?

I am messing around with this task for a while...

I am trying to call C# DLL methods from java.

I used this as a tutorial, and it suggests building an intermediate c++ dll. But it uses a method without an argument, and I am affraid that it needs a modification for using a method with an argument. This is becuase I get an unsatisfiedlinkerror exception when I call t.SetCounter0("aaa") function in java.

This is the java code:

package jniTester;

import java.io.Console;

public class Test1 {

static {
    //System.load("c:\\Users\\ttene\\Documents\\Visual Studio 2012\\Projects\\CPM\\CPMPerformanceCountersController\\x64\\Debug\\CppWrapperDll.dll");
    System.load("c:\\Users\\ttene\\Documents\\Cpm2Java\\CppWrapperDll.dll");
}

public native void SetCounter0(String x);

public static void main(String[] args) {

    try {
        Test1 t = new Test1();
        System.out.println("1");
        t.SetCounter0("aaa");
        System.out.println("2");

    } catch (Exception e) {
        e.printStackTrace();
    }
}

}

This is the cpp:

#include <jni.h>
#include <iostream>

#include "Java\jnicall.h"
#include "MCPP\CppWrapperDll.h"

JNIEXPORT void JNICALL Java_Test1_SetCounter0  (JNIEnv *jn, jobject jobj) {

    std::cout << "Java_Test1_SetCounter0";

    // Instantiate the MC++ class.
    CppWrapperDllC* t = new CppWrapperDllC();

    // The actual call is made. 
    t->callCountersControl();
}

This is the h file:

#using <mscorlib.dll>
#using "CountersControl.netmodule"

using namespace System;

public __gc class CppWrapperDllC
{
    public:
        // Provide .NET interop and garbage collecting to the pointer.
        CountersControl __gc *t;

        CppWrapperDllC() {

            t = new CountersControl();
            // Assign the reference a new instance of the object
        }

    // This inline function is called from the C++ Code
    void callCountersControl() {

        t->SetCounter0("aaa");
    }
};

And at last this is the jni h file:

#include <jni.h>
/* Header for class Test1 */

#ifndef _Included_Test1
#define _Included_Test1
#ifdef __cplusplus
extern "C" {
#endif
/*
 * Class:     Test1
 * Method:    SetCounter0
 * Signature: (Ljava/lang/String;)V
 */
JNIEXPORT void JNICALL Java_Test1_SetCounter0(JNIEnv *, jobject);

#ifdef __cplusplus
}
#endif
#endif

I'll appreciate you assistance. Thanks.

you should use javah to create JNI-headers. If you had used it, the declaration in the header would actually have looked like this:

JNIEXPORT void JNICALL Java_Test1_SetCounter0(JNIEnv *, jobject, jstring);

where jstring is the string passed as argument to SetCounter0(...) .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM