C++ 字符串函数C++;在目标C上运行时返回空++;
我尝试编写函数C++,并在ObjtryC++中运行它,但我总是接收空字符串而不是普通字符串。请帮帮我。 在文件C++ 字符串函数C++;在目标C上运行时返回空++;,c++,ios,objective-c,objective-c++,C++,Ios,Objective C,Objective C++,我尝试编写函数C++,并在ObjtryC++中运行它,但我总是接收空字符串而不是普通字符串。请帮帮我。 在文件Greeting.cpp中: #include "Greeting.hpp" string getVersion() { string version = "Hello C++"; return version; } 在文件Greeting.hpp #include <string> using namespace std;
Greeting.cpp
中:
#include "Greeting.hpp"
string getVersion() {
string version = "Hello C++";
return version;
}
在文件Greeting.hpp
#include <string>
using namespace std;
string getVersion();
在文件CoreWrapper.mm
#import "CoreWrapper.h"
@implementation CoreWrapper
+ (NSString*) greeting {
NSString *sAppleString = @(getVersion().c_str());
NSLog(@"Message == %@", sAppleString);
return sAppleString;
}
@end
sAppleString
始终返回空字符串。我不知道为什么?为了测试您的代码,我必须将以下内容添加到CoreWrapper.h
:
#import <Foundation/Foundation.h>
我得到了预期的输出:
Message == Hello C++
main: Hello C++
所以在我看来,你在一个更大的程序中遇到了一个问题,把代码缩减到你认为是什么导致了这个问题,但事实并非如此
还有几个额外的注意事项:
- 我不确定您的
指令是关于什么的,它们应该不是必需的#unde
CoreWrapper.h
:
#import <Foundation/Foundation.h>
我得到了预期的输出:
Message == Hello C++
main: Hello C++
所以在我看来,你在一个更大的程序中遇到了一个问题,把代码缩减到你认为是什么导致了这个问题,但事实并非如此
还有几个额外的注意事项:
- 我不确定您的
指令是关于什么的,它们应该不是必需的#unde
getVersion()
返回临时值,该值立即被销毁。之后,从c_str()
获取的指针将悬空。您不需要\ifdef\uu cplusplus\undef NO\undef YES\import“Greeting.hpp”\endif
部分。在CoreWrapper中导入“Greeting.hpp”。mm@songyuanyao不,它没有,字符串是复制的,我无法复制,如果我删除\ifdef\uu cplusplus\35; undef no#undef YES#import“Greeting.hpp”
它将抛出错误string
文件未找到?getVersion()
返回临时值,该值会立即被销毁。之后,从c_str()
获取的指针将悬空。您不需要\ifdef\uu cplusplus\undef NO\undef YES\import“Greeting.hpp”\endif
部分。在CoreWrapper中导入“Greeting.hpp”。mm@songyuanyao不,它没有,字符串是复制的,我无法复制,如果我删除\ifdef\uu cplusplus\35; undef no#undef YES#import“Greeting.hpp”
它会抛出错误string
文件未找到?问题是我调用NSString*str=[CoreWrapper Greeting]在.m
文件上。例如,我有xx.m文件,然后导入CoreWrapper.h
,所以仍然收到空字符串。您是否使用NSString*sAppleString=@(getVersion().c_str())代码>?问题是我在.m
文件上调用NSString*str=[CoreWrapper greeting]。例如,我有xx.m文件,然后导入CoreWrapper.h
,所以仍然收到空字符串。您是否使用NSString*sAppleString=@(getVersion().c_str())代码>?