2009-04-26 8 views
7

En utilisant PyObjC, est-il possible d'importer un module Python, d'appeler une fonction et d'obtenir le résultat comme (disons) un NSString?Est-il possible d'appeler un module Python depuis ObjC?

Par exemple, en faisant l'équivalent du code Python suivant:

import mymodule 
result = mymodule.mymethod() 

pseudo-ObjC ..dans:

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

double: http://stackoverflow.com/questions/49137/calling -python-de-ac-programme-pour-distribution; http://stackoverflow.com/questions/297112/how-do-i-use-python-libraries-in-c. Vous pouvez intégrer Python dans n'importe quelle application. –

+2

@ S.Lott Ce n'est pas un doublon; ces questions sont sur C++, pas Objective-C. Tandis que vous pouvez utiliser Objective-C++ pour mixer C++ et Objective-C, vous devrez vous-même emballer tout le code C++ dans les classes Objective-C si vous avez besoin de les utiliser comme classes Objective-C. –

Répondre

12

Comme mentionné dans la réponse d'Alex Martelli (bien que le lien dans le message liste de diffusion a été brisée, il devrait être https://docs.python.org/extending/embedding.html#pure-embedding) .. La façon C d'appeler ..

print urllib.urlopen("http://google.com").read() 
  • Ajouter Python. cadre de votre projet (clic droit External Frameworks.., Add > Existing Frameworks. Le cadre dans de /System/Library/Frameworks/
  • Ajouter à votre /System/Library/Frameworks/Python.framework/Headers "en-tête Chemin de recherche" (Project > Edit Project Settings)

Le code suivant devrait fonctionner (bien qu'il soit probablement pas le meilleur code jamais écrit ..)

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

Aussi this tutorial est bon

Questions connexes