2009-04-26 38 views
7

Usando PyObjC, ¿es posible importar un módulo Python, llamar a una función y obtener el resultado como (digamos) un NSString?¿Es posible llamar a un módulo de Python desde ObjC?

Por ejemplo, hacer el equivalente del siguiente código Python:

import mymodule 
result = mymodule.mymethod() 

..en pseudo-ObjC:

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

duplicado: http://stackoverflow.com/questions/49137/calling -python-from-ac-program-for-distribution; http://stackoverflow.com/questions/297112/how-do-i-use-python-libraries-in-c. Puede incrustar Python en cualquier aplicación. –

+2

@ S.Lott Esto no es un duplicado; esas preguntas son sobre C++, no Objective-C. Si bien puede usar Objective-C++ para mezclar C++ y Objective-C, debe envolver todo el código C++ en las clases Objective-C usted mismo si necesita usarlos como clases Objective-C. –

Respuesta

12

Como se mencionó en la respuesta de Alex Martelli (aunque el enlace en el mensaje de lista de correo se rompió, debería ser https://docs.python.org/extending/embedding.html#pure-embedding) .. La forma de llamar a C ..

print urllib.urlopen("http://google.com").read() 
  • Añadir al pitón. marco para su proyecto (Haga clic derecho External Frameworks.., Add > Existing Frameworks. El marco en el en /System/Library/Frameworks/
  • Añadir /System/Library/Frameworks/Python.framework/Headers a su "Ruta de búsqueda de cabecera" (Project > Edit Project Settings)

El siguiente código debería funcionar (aunque probablemente no es el mejor código que se ha escrito ..)

#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]; 
} 

También es bueno this tutorial

Cuestiones relacionadas