【问题标题】:Calling a C function messaging style, in objective-c在 Objective-C 中调用 C 函数消息传递样式
【发布时间】:2013-07-15 01:07:26
【问题描述】:

如果我有:

test.c

int test_func(){


        }

我想做:

test.m

[self test_func]

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

【问题讨论】:

  • 如果没有一些严重的偷工减料,你就无法做到这一点;除非您采取简单的路线,只需将test_func 设为调用test_func() 函数的实例方法。
  • 这应该是如何实现的……在某些特殊情况下,test_func() 可以以这样的方式定义,这是可能的(连同一些 objc 运行时调用来设置它),但是您需要解释您要解决的问题。一般的解决方案正如@dreamlax 所建议的那样。

标签: ios objective-c runtime objective-c-runtime


【解决方案1】:

可以以特殊方式声明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;
}

TestClass.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. Dynamic runtime resolution

  2. Using runtime API method class_addMethod

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-12-17
    • 2012-05-19
    • 1970-01-01
    相关资源
    最近更新 更多