MasterWizard
MasterWizard

Reputation: 877

Command Line C program to Swift

I have source code of a command line C game, that waits for user's stdin, and outputs stdout. I want to give input from a text field through to the main of this C code and take the output in a text area field for example.

int mainer(int argc, char **argv) {
    int i;
    int hitme;
    char ch;
    prelim();

    if (argc > 1) { // look for -f option
        if (strcmp(argv[1], "-f")== 0) {
            coordfixed = 1;
            argc--;
            argv++;
        }
    }


    if (argc > 1) {
        fromcommandline = 1;
        line[0] = '\0';
        while (--argc > 0) {
            strcat(line, *(++argv));
            strcat(line, " ");
        }
    }
    else fromcommandline = 0;
 // some other code

}

From the example here, I should do the following:

let args = [" ", "regular", "short", ""]

var cargs = args.map { strdup($0) }
let result = mainer(Int32(args.count), &cargs)
for ptr in cargs { free(ptr) }

How could I call the main function, and keep it alive and keep giving to it arguments to make it act as command line.

Upvotes: 15

Views: 760

Answers (3)

Fiid
Fiid

Reputation: 1840

I would set up your app with a TextArea and a TextField, and provide alternatives to printf and scanf that either add text to the text area or get sent text from the textfield (maybe with an "Enter" UIButton). Then you can compile the C code and call it from Swift. Objective C is actually C way under the covers, so you should be able to to get this to run with just a little alteration.

In order to get the code to run you'll probably have to make this code run in it's own thread, and jump through some hoops to get those calls to behave correctly, but it should be doable.

Upvotes: 2

Tali
Tali

Reputation: 869

Don't call that function in your process.

Instead, execute your command-line game as a separate process so that you can connect it's stdin/stdout to pipes. Then you can send the content of your text field into one pipe and read back the result from the other.

Have a look at e.g. http://practicalswift.com/2014/06/25/how-to-execute-shell-commands-from-swift/.

Upvotes: 0

xdeleon
xdeleon

Reputation: 779

I don’t think this is the right place to be doing this. The purpose of main is to essentially start up the app and then control passes to Application Delegate and proceeds from there. From Apple’s documentation: “With few exceptions, you should never change the implementation of the main function that Xcode provides.” https://developer.apple.com/library/ios/documentation/iPhone/Conceptual/iPhoneOSProgrammingGuide/TheAppLifeCycle/TheAppLifeCycle.html

There are other ways to mix C with Objective-C. If you need to call C the best place is likely the view where this data is needed. These links may help: Mixing C functions in an Objective-C class,

Upvotes: 0

Related Questions