我的C++代码,将字符串推送到mystack
#include <iostream>
#include <stack>
#include "NativeLogger.h"
std::stack<std::string> mystack;
JNIEXPORT void JNICALL
Java_NativeLogger_push(JNIEnv *env, jobject obj,jstring name)
{
std::string s = env->GetStringUTFChars(name, 0);
mystack.push(s);
return;
}
JNIEXPORT void JNICALL
Java_NativeLogger_pop(JNIEnv *env, jobject obj)
{
mystack.pop();
return;
}
使用 Java 运行时,我收到了以下崩溃报告,知道如何修复它吗?
A fatal error has been detected by the Java Runtime Environment:
SIGSEGV (0xb) at pc=0x00007f29421a0207, pid=18007, tid=0x00007f2942d3e700
JRE version: Java(TM) SE Runtime Environment (8.0_144-b01) (build 1.8.0_144-b01) Java VM: Java HotSpot(TM) 64-Bit Server VM (25.144-b01 mixed mode linux-amd64 compressed oops) Problematic frame: C [libc.so.6+0x97207] __libc_malloc+0x197
最佳答案
Java代码:
package recipeNo025;
public class HelloWorld {
public static native void pushString(String s);
public static native String popString();
static {
System.loadLibrary("HelloWorld");
}
public static void main(String[] args) {
HelloWorld.pushString("Hello");
System.out.println(HelloWorld.popString());
}
}
C++代码
#include <iostream>
#include <stack>
#include "jni.h"
#include "recipeNo025_HelloWorld.h"
std::stack<std::string> mystack;
JNIEXPORT void JNICALL Java_recipeNo025_HelloWorld_pushString
(JNIEnv *env, jclass obj, jstring str) {
// we have to get string bytes into C string
const char *c_str;
c_str = env->GetStringUTFChars(str, NULL);
if(c_str == NULL) {
return;
}
std::cout << "Passed string: " << c_str << std::endl;
std::string my_string(c_str);
mystack.push(my_string);
// after using it, remember to release the memory
env->ReleaseStringUTFChars(str, c_str);
}
JNIEXPORT jstring JNICALL Java_recipeNo025_HelloWorld_popString
(JNIEnv *env, jclass obj) {
std::string s = mystack.top();
mystack.pop();
return env->NewStringUTF(s.c_str());
}
执行:
> java -Djava.library.path=:./lib -cp target recipeNo025.HelloWorld
Passed string: Hello
Hello
此外,我还考虑过使用单例模式而不是使用堆栈的全局变量。
关于java - JNI、C++ 将字符串压入堆栈,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51471007/