【发布时间】:2018-05-15 09:22:54
【问题描述】:
我已尝试按照我在此处找到的示例进行操作,但无法使其正常工作。 这是我的 Java 类
package jniTester;
public class JNITester {
static {
System.load("D:\\\\VisualStudio_Cpp_2017\\SkriptumTeil5\\Debug\\HelloWorldJNI.dll");
}
public static native String welcome(String name);
}
由此我用 javah 创建了 jniTester.h 文件
这是我的 C# 类
namespace HelloWorldJNI
{
public static class HelloWorldJNI
{
public static String Welcome(String name)
{
return "Hello " + name + "! This is your C# buddy.";
}
}
}
由此我创建了 HelloWorldJNI.netmodule
这是我的 cpp 类
#include "stdafx.h"
#include <jni.h>
#include <string>
#include "jniTester.h"
#using "D:\VisualStudio_C#_2017\SkriptumTeil5\HelloWorldJNI\HelloWorldJNI.netmodule"
using namespace std;
JNIEXPORT jstring JNICALL Java_jniTester_JNITester_welcome(JNIEnv *env, jclass thisclass, jstring inJNIStr) {
// Step 1: Convert the JNI String (jstring) into C-String (char*)
const char *inCStr = env->GetStringUTFChars(inJNIStr, NULL);
if (NULL == inCStr) return NULL;
// Step 2: Convert the C++ string to C-string, then to JNI String (jstring) and return
//string outCppStr = "Hello " + std::string(inCStr) + ". Greetings from your C++ buddy";
//env->ReleaseStringUTFChars(inJNIStr, inCStr); // release resources
//return env->NewStringUTF(outCppStr.c_str());
//// Alternate Step 2:
System::String^ outStr = HelloWorldJNI::HelloWorldJNI::Welcome(gcnew System::String(inCStr));
env->ReleaseStringUTFChars(inJNIStr, inCStr); // release resources
char* converted = static_cast<char*>((System::Runtime::InteropServices::Marshal::StringToHGlobalAnsi(outStr)).ToPointer());
return env->NewStringUTF(converted);
}
第 2 步下的代码有效。但是,这不是调用我的 C# 方法。 替代步骤 2 下的实施失败,并显示
# A fatal error has been detected by the Java Runtime Environment:
#
# Internal Error (0xe0434352), pid=37224, tid=0x00003350
我不是 cpp 专家,所以我完全一无所知。这里有什么问题?
【问题讨论】:
-
在您的 JNI 函数实现周围添加
export "C" { /* my JNI functions */ }。由于您使用 C++ 来包装 C#。还要检查 - 如何call managed code from the native code -
感谢您的快速回答。但是,我无法使用导出语句。它已经在 Visual Studio 中产生语法错误
-
检查你的类库。 See also
-
抱歉,我不知道在哪里检查什么
-
忘记
export "C"的东西。首先是extern而不是export。其次,它必须已经在标题中,否则您根本无法调用该函数。您是否尝试过调用不带参数的 C# 函数?您是否尝试过独立的 C++ 可执行文件?这不太可能是 JNI 问题。
标签: java c# java-native-interface