c的注意事项

注意事项

oc 调用 c c++ 需要注意的地方

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
#ifndef LearnC_h
#define LearnC_h
#include <stdio.h>
#ifdef __cplusplus
extern "C" {
#endif
void learnCplus(int a, int b);
#ifdef __cplusplus
}
#endif
#endif /* LearnC_h */

hpp

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
#ifndef LearnC___hpp
#define LearnC___hpp
#include <string>
#include <stdio.h>
void learnCplusplus(int a, int b);
class cppObject
{
public:
void exampleMethod(const std::string& str);
};
#endif /* LearnC___hpp */

cpp

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
//
// LearnC++.cpp
// LearnOCandCandC++
//
// Created by 林伟池 on 16/2/23.
// Copyright © 2016年 林伟池. All rights reserved.
//
#include "LearnC++.hpp"
#include <iostream>
void learnCplusplus(int a, int b) {
printf("cplusplus%d\n", a + b);
}
void cppObject::exampleMethod(const std::string &str)
{
std::cout << str;
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
#import "LearnC.h"
#import "LearnC++.hpp"
#import "LearnOCinCPP.h"
@interface ViewController ()
@end
@implementation ViewController
{
cppObject* object;
}
- (void)viewDidLoad {
[super viewDidLoad];
learnCplus(1, 2); //在OC中使用c
learnCplusplus(1, 2); //在OC中用C++编译的C
//在OC中使用C++的类
object = new cppObject();
NSString* str = @"GAO高级\n";
std::string cpp_str([str UTF8String], [str lengthOfBytesUsingEncoding:NSUTF8StringEncoding]);
object->exampleMethod(cpp_str);
delete object;
object = NULL; //记得删除
//在OC使用的C++类中 使用OC
LY::OCinCPP* cpp = new LY::OCinCPP();
cpp->lyRun();
}

参考