-2

if I have:

test.c

int test_func(){


        }

And I wanted to do :

test.m

[self test_func]

How should my .h files be set up with respect to the test.c file. I have seen a question like this answered here but I failed to bookmark it, and I can't track it down. It involved an .h file with an extern command. Any help would be appreciated.

dreamlax
  • 93,976
  • 29
  • 161
  • 209
cube
  • 1,774
  • 4
  • 23
  • 33
  • 3
    You can't do that without some serious jerry-rigging; unless you take the simple route and just make `test_func` an instance method that calls the `test_func()` function. – dreamlax Jul 15 '13 at 01:10
  • 1
    Which is exactly how it should be implemented… There are special cases where `test_func()` could be defined in such a way that this is possible (together with some objc runtime calls to set it up), but you would need to explain what problem you're trying to solve. The general solution is as @dreamlax suggests. – Rob Napier Jul 15 '13 at 01:16

1 Answers1

1

It is possible to declare test_func in a special way and use various Objective-C runtime API functions to “attach” that method implementation to a class's method list, but the simplest way to do this:

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

If you are still keen to try adding methods at runtime, have a look at these links:

  1. Dynamic runtime resolution

  2. Using runtime API method class_addMethod

It is worth noting that for anything as trivial as calling a C function you should avoid dynamic method injection/resolution for the sake of maintainability and readability. Unless you have an ulterior motive that you haven't explained in your question, stick with Plan A (the simple route)!

dreamlax
  • 93,976
  • 29
  • 161
  • 209