2009-04-26 16 views
7

Utilizzando PyObjC, è possibile importare un modulo Python, chiamare una funzione e ottenere il risultato come (diciamo) un NSString?È possibile chiamare un modulo Python da ObjC?

Ad esempio, facendo l'equivalente del seguente codice Python:

import mymodule 
result = mymodule.mymethod() 

..nel pseudo-objC:

PyModule *mypymod = [PyImport module:@"mymodule"]; 
NSString *result = [[mypymod getattr:"mymethod"] call:@"mymethod"]; 
+0

Duplicate: http://stackoverflow.com/questions/49137/calling -python-da-ac-programma-per-distribuzione; http://stackoverflow.com/questions/297112/how-do-i-use-python-libraries-in-c. Puoi incorporare Python in qualsiasi applicazione. –

+2

@ S.Lott Questo non è un duplicato; quelle domande riguardano C++, non Objective-C. Mentre puoi usare Objective-C++ per mixare C++ e Objective-C, dovresti inserire tu stesso tutto il codice C++ nelle classi Objective-C se devi usarli come classi Objective-C. –

risposta

12

Come accennato nella risposta di Alex Martelli (anche se il link nel messaggio mailing-list è stato rotto, dovrebbe essere https://docs.python.org/extending/embedding.html#pure-embedding) .. Il modo C di chiamare ..

print urllib.urlopen("http://google.com").read() 
  • Aggiungere il Python. quadro di riferimento per il progetto (Fare clic destro External Frameworks.., Add > Existing Frameworks. Il quadro in in /System/Library/Frameworks/
  • Aggiungi /System/Library/Frameworks/Python.framework/Headers al "Intestazione percorso di ricerca" (Project > Edit Project Settings)

Il seguente codice dovrebbe funzionare (anche se non è probabilmente il miglior codice mai scritto ..)

#include <Python.h> 

int main(){ 
    NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init]; 
    Py_Initialize(); 

    // import urllib 
    PyObject *mymodule = PyImport_Import(PyString_FromString("urllib")); 
    // thefunc = urllib.urlopen 
    PyObject *thefunc = PyObject_GetAttrString(mymodule, "urlopen"); 

    // if callable(thefunc): 
    if(thefunc && PyCallable_Check(thefunc)){ 
     // theargs =() 
     PyObject *theargs = PyTuple_New(1); 

     // theargs[0] = "http://google.com" 
     PyTuple_SetItem(theargs, 0, PyString_FromString("http://google.com")); 

     // f = thefunc.__call__(*theargs) 
     PyObject *f = PyObject_CallObject(thefunc, theargs); 

     // read = f.read 
     PyObject *read = PyObject_GetAttrString(f, "read"); 

     // result = read.__call__() 
     PyObject *result = PyObject_CallObject(read, NULL); 


     if(result != NULL){ 
      // print result 
      printf("Result of call: %s", PyString_AsString(result)); 
     } 
    } 
    [pool release]; 
} 

anche this tutorial è buono

Problemi correlati