oc与c语言的相互调用

一: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;

}

 

 

转载于:https://www.cnblogs.com/mcy0808/p/7657495.html

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值