2009-04-26 28 views
7

PyObjC'yi kullanarak, bir Python modülünü içe aktarmak, bir işlevi çağırmak ve sonucu bir NSString olarak almak mümkün mü?ObjC'den bir Python modülü çağırmak mümkün mü?

import mymodule 
result = mymodule.mymethod() 

..in sözde objc: Aşağıdaki Python kodu eşdeğerini yapmanın Örneğin

,

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

Yinelenen: http://stackoverflow.com/questions/49137/calling -python-den-ac-program için dağılımının; http://stackoverflow.com/questions/297112/how-do-i-use-python-libraries-in-c. Python'u herhangi bir uygulamaya gömebilirsiniz. –

+2

@ S.Lott Bu bir kopya değil; Bu sorular C++, Objective-C ile ilgili değildir. C++ ve Objective-C'yi karıştırmak için Objective-C++ özelliğini kullanabilmeniz için Objective-C sınıfları olarak kullanmanız gerekiyorsa, Object-C sınıflarındaki tüm C++ kodunu kendiniz sarmanız gerekir. –

cevap

12

..

print urllib.urlopen("http://google.com").read() 
  • Python ekleyin. projenize çerçeve (Sağ External Frameworks.., Add > Existing Frameworks tıklayın. çerçeveyi içinde /System/Library/Frameworks/
  • içinde "Başlık Arama Yolu" /System/Library/Frameworks/Python.framework/Headers ekle (Project > Edit Project Settings)
Aşağıdaki kod çalışması gerekir

(muhtemelen şimdiye kadar yazılmış en iyi kod olmasa da ..)

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

Ayrıca this tutorial iyidir

3

oldukça AFAIK, fakat yapabileceğin it "C Örneğin, http://lists.apple.com/archives/Cocoa-dev/2004/Jan/msg00598.html'da önerildiği şekilde veya http://osdir.com/ml/python.pyobjc.devel/2005-06/msg00019.html'a göre "Pyobjc yolunda" olduğu gibi (daha fazla açıklama için bu konudaki tüm diğer mesajlara bakın).

.. (e-posta liste mesajında ​​bağlantı kesildi rağmen, https://docs.python.org/extending/embedding.html#pure-embedding olmalıdır) Alex Martelli yanıtında çağıran C yolunu belirtildiği gibi