无法解析类型“std::string”。

3

我开始将一些Java代码移植到Android的本地C++中。我在使用C++字符串时遇到了一个问题:

Type 'std::string' could not be resolved

这是我的样例代码。
#include <jni.h>
#include <lexu_me_test_native.h>
#include <string.h>
using namespace std;

JNIEXPORT jstring JNICALL Java_lexu_me_test_native_prepairToShowNative
  (JNIEnv * env, jclass javaThis, jstring str)
{
    jboolean blnIsCopy;
    jstring jstrOutput;
    char* strCOut;
    std::string ss;

    const char* strCIn = (env)->GetStringUTFChars(str , &blnIsCopy);
    // convert jstring to a char array
    // Do stuff with the char array and and store the result
    // in another char array strCOut
    (env)->ReleaseStringUTFChars(str , strCIn); // release jstring

    jstrOutput = (env)->NewStringUTF(strCOut); // convert char array to jstring
    return jstrOutput;
}

Android.mk文件:

LOCAL_PATH := $(call my-dir)

include $(CLEAR_VARS)

LOCAL_MODULE    := native
LOCAL_SRC_FILES := native.cpp

include $(BUILD_SHARED_LIBRARY)

Application.mk文件:

APP_STL := stlport_static

已安装MinGW并添加至环境变量。我尝试使用android-ndk-r8e和android-ndk-r8-crystax-1,但都不能解决问题。在Cygwin终端中出现了错误:

Compile++ thumb  : native <= native.cpp
jni/native.cpp: In function '_jstring* Java_lexu_me_test_native_prepairToShowNative(JNIEnv*, jclass, jstring)':
jni/native.cpp:11:2: error: 'string' was not declared in this scope
jni/native.cpp:11:9: error: expected ';' before 'ss'

我正在使用Win 7 64位操作系统。有人能说一下如何解决吗? 谢谢。
编辑。
在C/C++常规-路径和符号中已经设置为:C:\Android\android-ndk-r8e\platforms\android-14\arch-arm\usr\include

3
#include <string><string.h> 是一个C语言库头文件。 - jrok
使用命名空间std; 尝试使用string而不是std :: string。 - Jite
8
不要建议这样做。使用命名空间std是一种不好的编程实践。(参考链接:https://dev59.com/D3M_5IYBdhLWcg3wQQ3w) - Rapptz
@Rapptz 是的,我也有同感,但不管是不是不好的实践,如果使用了,就应该正确地使用 :P - Jite
1
正确使用 using namespace std; 的方法根本就不存在。 - The Forest And The Trees
显示剩余4条评论
2个回答

1
如果其他答案不起作用,那么请尝试以下步骤:
  1. 如果你使用了using namespace std;,请使用string代替std::string
  2. 如果#include <string>无法工作且你正在使用Linux,请尝试#include <unistd.h>。如果你使用的是其他操作系统,请使用#include <cstdlib>

嗨,我已将 std::string 更改为 string,并添加了 #include <string>。但是 Eclipse 显示错误“无法解析类型 'string'”,尽管在 cygwin 中编译正常。 - LEX
然后Eclipse出了问题,但我建议您尝试在Windows上使用#include <cstdlib>或在Linux上使用#include <unistd.h>而不是#include <string> - Shervin Sorouri
#include <cstdlib> Eclipse 接受了它,但警告没有隐藏,在 cygwing 中编译时显示错误“'string' was not declared in this scope”。 - LEX
如果你是Windows用户,我推荐使用Visual Studio,因为它非常易于使用,并且是免费的。请前往微软网站查看。 - Shervin Sorouri
但是Eclipse显示错误“无法解析类型'string'”,尽管在cygwin中编译正常...另请参见Android NDK构建,方法无法解析。Eclipse和插件在NDK更新期间崩溃,从未修复。这可能是因为Android Studio不支持JNI而从未修复... - jww
显示剩余2条评论

-1
请检查您的 Android.mkApplication.mk 文件。确保您选择了一个 STL 库并在 Application.mk 文件中进行了包含:
Application.mk: APP_STL := gnustl_static

(gnustl_static) 可以被替换为您想要的STL版本,而STLPort仍然是一个选择

请参见http://www.kandroid.org/ndk/docs/CPLUSPLUS-SUPPORT.html


这并不是对问题的回答。如果你想提出批评或请求作者澄清,请在他们的帖子下面留言。 - Parag Bafna
哇,这是很久以前的事了。我会更新答案。不过,请参考http://www.kandroid.org/ndk/docs/CPLUSPLUS-SUPPORT.html。 - Joe Plante

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接