一:OC调用C语言
C语言的.h文件
//
// TestPrint.h
// TestDemo
//
// Created by Techsun on 14-8-12.
// Copyright (c) 2014年 techsun. All rights reserved.
//
#ifndef TestDemo_TestPrint_h
#define TestDemo_TestPrint_h
void printlog();
#endif
C语言中.c文件
//
// TestPrint.c
// TestDemo
//
// Created by Techsun on 14-8-12.
// Copyright (c) 2014年 techsun. All rights reserved.
//
#include <stdio.h>
#include "TestPrint.h"
void printlog(){
printf("hello world !!!");
}
OC的.m文件
//
// AClass.m
// TestDemo
//
// Created by Techsun on 14-8-12.
// Copyright (c) 2014年 techsun. All rights reserved.
//
#import "AClass.h"
#import "TestPrint.h"
@implementation AClass
- (void)printfhello{
printlog();
}
@end
二:C语言调用OC
1)方式1:c++直接包含oc头文件,编译时加入连接选项
main.cpp
#include "CppFile.h"
#include <memory>
int main(int argc, char** argv)
{
std::shared_ptr<CppFile> cppfile(new CppFile());
cppfile->print_cpp_Msg();
cppfile->print_oc_Msg();
return 0;
}
CppFile.h
#ifndef __CPP_FILE__
#define __CPP_FILE__
class CppFile
{
public:
void print_cpp_Msg();
void print_oc_Msg();
};
#endif
CppFile.mm 因为CppFile中使用OC相关的函数,所以我们需要import
#include <iostream>
#import <Foundation/Foundation.h>
#include "CppFile.h"
void CppFile::print_cpp_Msg()
{
std::cout << "This is cpp file msg" << std::endl;
}
void CppFile::print_oc_Msg()
{
NSLog(@"This is object-c msg");
}
编译及运行
在编译的时候需要加上-framework Foundation的参数,否则会提示找不到”_NSLog”定义。
Compile:
#compile cpp file
clang++ -g -O2 -Wall -std=c++11 -c main.cpp
#compile oc file
clang++ -g -O2 -Wall -std=c++11 -c CppFile.mm -framework Foundation
#link object
clang++ -o test main.o CppFile.o -framework Foundation2)OC实现回调函数,并传递给C
1、参数传递
1.1 全局:自定义一种CallBackFunc类型的函数指针
typedef void (*CallBackFunc)(param);
1.2 在类 A(OC)中
定义回调函数的实现:
voidplayCallback(param)
{
//NSLog(@"loginCallback");
}
同时,调用类B的函数,同时把playCallback作为参数传递过去
void B::setCallBack(playCallback);
1.3 在类B(C++)中定义类型为CallBackFunc的函数指针:
CallBackFuncpCallBackFunc;
void B::setCallBack(CallBackFunc pcallbackFunc)
{
this->pCallBackFunc = pcallbackFunc;
}
原文链接: https://www.cnblogs.com/mcy0808/p/7657495.html
欢迎关注
微信关注下方公众号,第一时间获取干货硬货;公众号内回复【pdf】免费获取数百本计算机经典书籍
原创文章受到原创版权保护。转载请注明出处:https://www.ccppcoding.com/archives/261207
非原创文章文中已经注明原地址,如有侵权,联系删除
关注公众号【高性能架构探索】,第一时间获取最新文章
转载文章受原作者版权保护。转载请注明原作者出处!