在objective-C中调用C函数消息传递样式



如果我有:

test.c

int test_func(){

        }

我想做:

test.m

[self test_func]

相对于test.c文件,应该如何设置我的.h文件。我在这里看到了这样一个问题的答案,但我没有将其添加到书签中,也无法找到它。它涉及一个带有extern命令的.h文件。如有任何帮助,我们将不胜感激。

可以通过特殊方式声明test_func,并使用各种Objective-C运行时API函数“附上";方法实现到类的方法列表,但最简单的方法是:

testfunc.h

#ifndef TESTFUNC_H
#define TESTFUNC_H
int test_func();
#endif

testfunc.c

#include "testfunc.h"
int test_func()
{
    return 4;
}

测试类.h

#import <Foundation/Foundation.h>
@interface TestClass : NSObject
- (int) test_func;
@end

testclass.m

#import "TestClass.h"
#import "testfunc.h"
@implementation TestClass
- (int) test_func
{
    return test_func();
}
@end

如果您仍然热衷于在运行时尝试添加方法,请查看以下链接:

  1. 动态运行时分辨率

  2. 使用运行时API方法class_addMethod

值得注意的是,对于像调用C函数这样琐碎的事情,出于可维护性和可读性的考虑,应该避免动态方法注入/解析。除非你有不可告人的动机,你没有在问题中解释,否则坚持A计划(简单的路线)!

最新更新