【发布时间】:2015-05-23 16:13:05
【问题描述】:
问题描述:
我的项目是 JAVA,但我想调用一个 C++ 函数,它将一个字符串作为输入并在处理后输出另一个字符串。我应用JNA来做这个工作,String和char*是JAVA到C++的映射类型。(在处理过程中,我需要std::string作为中间类型,详细给出了简化代码。)
当输入字符串不长时,程序运行良好。然而,当我增加字符串的长度时(这里,我重复了“test sentence ...”6次),事情开始变得奇怪了。我可以看到字符串在 C++ 程序中传递(成功打印出来),但是我在 JAVA 中收到了一个空字符串,这意味着它无法返回字符串。更重要的是,每次执行的while循环次数都不一样(中断循环时打印出不同的计数)。
那么,
1.长度有什么问题? JNA 有什么限制吗?
2。我可以达到我的目标以及如何在 JNA 中正确传递字符串吗?(顺便说一句,我尝试过指针的东西,但它不起作用)
谢谢,这是我的代码和一些环境细节
C++ 端代码>>>>>>>>>>>test.cpp
#include<iostream>
using namespace std;
extern "C" __attribute__((visibility("default"))) const char* SeudoCall(const char* input);
const char* SeudoCall(const char* str){
std::string input(str);
std::cout<<"in C:"<<input<<std::endl;
return input.c_str();
}
编译 C++ 库>>>>>>>>>
g++ test.cpp -fpic -shared -o libtest.so
JAVA 端代码>>>>>>>>>>
import com.sun.jna.Library;
import com.sun.jna.Native;
public class TestSo {
public interface LgetLib extends Library {
LgetLib INSTANCE = (LgetLib) Native.loadLibrary("test", LgetLib.class);
String SeudoCall(String input);
}
public String SeudoCall(String input){
return LgetLib.INSTANCE.SeudoCall(input);
}
public static void main(String[] args) {
TestSo ts = new TestSo();
String str = "test sentence...test sentence...test sentence...test sentence...test sentence...test sentence...";
String retString;
int count=0;
while(true){
System.out.println("count:"+(++count));
retString=ts.SeudoCall(str);
System.out.println("in JAVA:"+retString);
if(retString.equals("")){
System.out.println("break");
break;
}
}
}
}
运行细节>>>>>>>>>>
Intel Core i7-4790 3.60GHz
gcc version 4.8.2 (Ubuntu 4.8.2-19ubuntu1)
JNA 4.1.0
java version "1.8.0_31"
Java(TM) SE Runtime Environment (build 1.8.0_31-b13)
Java HotSpot(TM) 64-Bit Server VM (build 25.31-b07, mixed mode)
【问题讨论】: