I’m trying to figure out how to call a C function from ASOC.
I created two files mathSum.h with code…
int sum (int x, int y);
and mathSum.c with code… #include “mathSum.h”
int sum (int x, int y)
{
return (x + y);
}
In my AppDelegate.applescript I have…
property parent : class “NSObject”
property textField : missing value
property myCcall : class “mathSum”
on runCcode_(sender)
set myCall to mathSum's alloc()'s init()
myCall's sum(10, 11)
textField's setStringValue_(myCall's sum(10, 11) as string)
end runCcode_
…But I get an error that mathSum is not defined… How do I make a call to C? Thanks!!!
property myCcall : class “mathSum” should have read
property myCall : class “mathSum” … But still get same error. Not sure how to call a C function from ASOC.
You Can’t call C functions from ASOC. ASOC is only able to call selectors, which are null terminated strings pointing to an pointer function in C. To make it possible to call C functions indirectly is creating an Objective-C wrapper around it. This way you have a pointer to an function in your Objective-C run time and this function is running C code like this
This way you have wrapped Objective-C code around C function strlen.
Sorry, this is not enough information for me to understand. How do I go about calling the simple C functions I have stated above indirectly? What files do I make and how is it called from ASOC?
I was able to make this work. Thank you… Suppose I have some files written in just C and not ObjC… do I need to rewrite them in ObjC or is there another way to add the files to my project and be able to use them in ASOC?
As far as I know, you do have to redo them in objective-c, although “rewrite” might be too strong a word. You can put whatever c code you want inside your objective-c methods as long as the method signature has all the arguments you need to get your c code to work. So, mostly it’s just the name of the function that you have to create (and maybe some conversions to c types), the insides can still be all c, and shouldn’t require much rewrite.
I’m still using 10.6 but I read somewhere that in 10.7/Lion it is possible to call a C-routine from AppleScript if you tell the current application: “tell current application to NSRectFill(aRect)”. Does this work with every C-routine or only with routines in Apple’s frameworks?
Only with those in Foundation, from memory. I believe it should be all frameworks with bridge support files, provided they are loaded at launch time, but the test I did when it came out suggests this was not the case. And in practice, only a selection are usable because many require structures ASObjC can’t handle. ASObjC is limited to a handful: NSRange, NSSize, NSPoint, and NSRect.
It’s not possible like I said before unless some C functions are defined as selectors (with NULL objects) in the Objective-C runtime or by the AppleScriptObjC framework. But still they’re always selectors and never functions that you actually call.