最近做个项目需要用到C++与Objective C混合编程,下面的代码用于将NSString类型数据转换为string类型数据,NSDictionary类型数据转换为map类型数据,发现在objective C中引用C++头文件会出错,捣鼓了半天,发现这样做可以解决:
1.将.m文件扩展名改为.mm,或者修改.m文件的File Type,改为Objective C++ Source.
2.将.h文件File Type改为Objective C++ Preprocessed Source,默认C Header.
//
// PlatformCommon.h
// LibObject
//
// Created by chen yang on 13-3-20.
// Copyright (c) 2013年 admin. All rights reserved.
//
#import <Foundation/Foundation.h>
#import <iostream>
#import <map>
#define NSStringToString(str) (str != nil ? [str UTF8String] : "")
#define StringToNSString(str) [NSString stringWithUTF8String:str.c_str()]
@interface PlatformCommon : NSObject
+ (std::map<std::string, std::string> )NSDictionaryToMap:(NSDictionary *)params;
@end
//
// PlatformCommon.mm
// LibObject
//
// Created by chen yang on 13-3-20.
// Copyright (c) 2013年 admin. All rights reserved.
//
#import "PlatformCommon.h"
#import <iostream>
#import <map>
using namespace std;
@implementation BlcPlatformCommon
+ (std::map<std::string, std::string> )NSDictionaryToMap:(NSDictionary *)params
{
NSArray *allKeys = [params allKeys];
std::map<std::string, std::string> mapParams;
for (NSString *key in allKeys)
{
mapParams[NSStringToString(key)] = NSStringToString([params objectForKey:key]);
}
return mapParams;
}
@end