Swift:String.fromCString()没有';我有时不工作

Swift:String.fromCString()没有';我有时不工作,swift,macos,Swift,Macos,环境:Xcode 7.2.1、Swift 2.1.1、OS X 10.11.3 首先,我使用Xcode创建一个osx项目(Cocoa应用程序) 然后添加一个简单的C++文件,如下: #include <stdio.h> #include <string> extern "C"{ const char* test() { //std::string abc = "abc"; //std::string abc = "abcdeabcde"; //s

环境:Xcode 7.2.1、Swift 2.1.1、OS X 10.11.3

首先,我使用Xcode创建一个osx项目(Cocoa应用程序)

然后添加一个简单的C++文件,如下:

#include <stdio.h>
#include <string>

extern "C"{
const char* test() {
    //std::string abc = "abc";
    //std::string abc = "abcdeabcde";
    //std::string abc = "abcdeabcdeabcde";
    std::string abc = "abcdefghijklmnopqrstuvwxyabcdefghijklmnopqrstuvwxyabcdefghijklmnopqrstuvwxyabcdefghijklmnopqrstuvwxyabcdefghijklmnopqrstuvwxyabcdefghijklmnopqrstuvwxyabcdefghijklmnopqrstuvwxyabcdefghijklmnopqrstuvwxyabcdefghijklmnopqrstuvwxyabcdefghijklmnopqrstuvwxyabcdefghijklmnopqrstuvwxyabcdefghijklmnopqrstuvwxyabcdefghijklmnopqrstuvwxyabcdefghijklmnopqrstuvwxyabcdefghijklmnopqrstuvwxyabcdefghijklmnopqrstuvwxyabcdefghijklmnopqrstuvwxyabcdefghijklmnopqrstuvwxyabcdefghijklmnopqrstuvwxyabcdefghijklmnopqrstuvwxyabcdefghijklmnopqrstuvwxyabcdefghijklmnopqrstuvwxyabcdefghijklmnopqrstuvwxyabcdefghijklmnopqrstuvwxyabcdefghijklmnopqrstuvwxyabcdefghijklmnopqrstuvwxyabcdefghijklmnopqrstuvwxyabcdefghijklmnopqrstuvwxyabcdefghijklmnopqrstuvwxyabcdefghijklmnopqrstuvwxyabcdefghijklmnopqrstuvwxyabcdefghijklmnopqrstuvwxyabcdefghijklmnopqrstuvwxyabcdefghijklmnopqrstuvwxyabcdefghijklmnopqrstuvwxyabcdefghijklmnopqrstuvwxy";

    return abc.data();
}
}
cpp文件中4个字符串值的结果如下所示:

  • 成功,结果是:abc
  • 错误,结果为:abciݿ
  • 错误
    转换结果
    为零,控制台将告诉您“致命错误:在展开可选值时意外发现零”
  • 有时成功,按定义打印超长字符串,而另一个则不打印

  • 我每天搜索谷歌和StAdvOp溢出,找到这个bug的任何东西。

    < p>你的C++函数<代码>测试())/Cux>有未定义的行为。您不能使用它生成有效的C字符串,因为对其调用
    data()
    的变量
    std::string abc
    ,是
    test()
    函数的本地变量

    这就是为什么从
    test()
    返回的值在返回时变得无效的原因:对变量
    abc
    调用析构函数,释放其数据并使返回成为无效的“悬空”指针

    出于测试目的,您可以将
    abc
    设置为静态,并调用
    c_str()
    而不是
    data()


    这将解决问题,因为函数静态对象不会在从函数返回时被销毁。

    完全正确!谢谢你的回答。
    func applicationDidFinishLaunching(aNotification: NSNotification) {
        // Insert code here to initialize your application
        let origin = test()
        let convertResult = String.fromCString(origin)
        print(convertResult!)
    }
    
    static std::string abc = "...";
    return abc.c_str();