Re: ObjC from C
Re: ObjC from C
- Subject: Re: ObjC from C
- From: Simon Stapleton <email@hidden>
- Date: Fri, 14 Dec 2001 17:24:09 +0000 (GMT)
>
Subject: Re: ObjC from C
>
Cc: email@hidden
>
To: jgo <email@hidden>
>
From: Charles Srstka <email@hidden>
>
>
Have you tried doing this? I guess there might be something I'm not
>
understanding, but for what I know, this should work fine. I did
>
something kind of similar to this for a while with Pacifist. I
>
eventually ended up converting the C function to a nice Obj-C
method,
>
but still...
>
>
On Friday, December 14, 2001, at 12:32 AM, jgo wrote:
>
>
>> Really, he's telling the truth. Rename the .c file so it
>
>> ends with .m. Import the headers for the class you want
>
>> to call the methods from. This should work.
>
>
>
> You're supplying an answer for something different from the
>
> question asked... or at least the question I have in mind.
>
>
>
> Let's say I have a laboriously built, maintained & accumulated
>
> set of C functions; it's been 15 years in the making. Let's
>
> say it is in a single pair of files b.h and b.c
>
>
>
> Now, I'm in Cocoa-land, and I've put together part of a program
>
> (in a.h and a.m), and want to make use of the function
>
> SInt16 myWonderfulCFunction(SInt32 d)
>
> inside of a.m
>
>
>
> Well, of course, I'd have to include (or could I import?)
>
> b.h but then would it scream when I wrote
>
> - (int) myWonderfulCocoaMethodUsingBool: (BOOL) what
>
> {
>
> int e;
>
> //...
>
> e = f * g;
>
> return (myWonderfulCFunction(e));
>
> }
>
>
>
>
>
> And then, we should have an example the other way 'round, with
>
> an invocation of an Objective C method from a C function...
>
> if that's workable. Though I see Marcel has written something
>
> to the effect that it is workable... only not written in
>
> decipherable AmerEnglish.
John.
There's absolutely nothing wrong with the code you posted. It will
work 100%, no errors, no screams. Substitute 'NSLog'
for 'myWonderfulCFunction' and then tell me it shouldn't.
You can call any 'C' function that the compiler knows about (i.e. has
imported headers for) from any Objective-C method.
The other way around, there are some caveats.
The call must be from an Objective-C file (i.e. a .m file or one
which the compiler has been told to treat as Objective-C).
The method you're calling must either be a class method (i.e. +(void)
mySelector;) or you must have an instance of an objective-C class.
Thusly, assuming you have a class 'myClass' with the following methods
+(void)mySelector;
-(void)anotherSelector;
the following holds:
int myFunction ()
{
id object = [[myClass alloc] init];
id anotherObject = nil;
[myClass mySelector]; //will work
[myClass anotherSelector]; //will not work
[object anotherSelector]; // will work
[anotherObject anotherSelector]; //will not work
...etc
}
Simon
--
PGP Key ID : 0x50D0698D
--
If the answer isn\'t obvious, the question is a distraction. Go find
an easier question.