一: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 Foundation
2)OC實現回調函數,並傳遞給C
1、參數傳遞
1.1 全局:自定義一種CallBackFunc類型的函數指針
typedef void (*CallBackFunc)(param);
1.2 在類 A(OC)中
定義回調函數的實現:
void playCallback(param)
{
//NSLog(@"loginCallback");
}
同時,調用類B的函數,同時把playCallback作為參數傳遞過去
void B::setCallBack(playCallback);
1.3 在類B(C++)中定義類型為CallBackFunc的函數指針:
CallBackFunc pCallBackFunc;
void B::setCallBack(CallBackFunc pcallbackFunc)
{
this->pCallBackFunc = pcallbackFunc;
}
