[英]How to call a function with arguments in C++ from JAVA using JNI?
我忙了一段時間
我正在嘗試從Java調用C#DLL方法。
我將其用作教程,它建議構建一個中間的c ++ dll。 但是它使用了不帶參數的方法,而我深感它需要修改以使用帶參數的方法。 這是因為當我在Java中調用t.SetCounter0(“ aaa”)函數時,我得到了一個unsatisfiedlinkerror異常。
這是java代碼:
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();
}
}
}
這是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();
}
這是h文件:
#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");
}
};
最后是jni h文件:
#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
多謝您的協助。 謝謝。
您應該使用javah創建JNI標頭。 如果您使用過它,則標題中的聲明實際上將如下所示:
JNIEXPORT void JNICALL Java_Test1_SetCounter0(JNIEnv *, jobject, jstring);
其中jstring是作為參數傳遞給SetCounter0(...)
的字符串。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.