2009-09-19 131 views
2

我有一個使用PyObjC完全用Python編寫的插件,其核心類需要轉換爲Objective-C。其中一個基本上只是加載一個Python模塊並執行一個特定的函數,並傳遞給它關鍵字參數。在PyObjC中,這非常棒。如何將NSDictionary轉換爲Python字典?

但是,我很難搞清楚如何使用Python C API來做同樣的事情。特別是,我不確定如何將NSDictionary(可能包含整數,字符串,布爾值或所有上述內容)轉換爲可以作爲關鍵字參數傳遞給Python的格式。

任何人都有關於如何完成這樣的事情的指針?提前致謝!

編輯:爲了澄清,我將原來的Python轉換爲Objective-C,並且無法找出如何從Objective-C中的NSDictionary移動到Python字典中。當我調用其餘的Python腳本時傳遞。 Objective-C類基本上只是一個Python加載器,但我對Python C API不熟悉,並且無法找到哪些示例或函數可以幫助我。

+0

我有點驚訝,你不能只是通過PyObjC將NSDictionary傳遞到Python,然後把它像一個普通的Python字典。有沒有具體的東西沒有用? – bbum 2009-09-20 00:43:54

+0

可能只是我的知識,如何做到這一點;關心如何使用PyObjC從Objective-C類中調用Python函數並將其傳遞給NSDictionary? PyObjC的C API文檔也很棒;看起來卻找不到任何東西。 – 2009-09-20 15:38:49

+0

其實,沒有必要的代碼;我沒有注意到邁克爾已經在下面第二次回答我了!哎呦。 :-) – 2009-09-20 15:47:52

回答

2

哦,看起來像我誤解了你的問題。那麼,走向另一個方向並不是非常不同。這應該是(至少作爲一個開始)你正在尋找的功能(我沒有測試它徹底的,所以蟲子的提防):

// Returns a new reference 
PyObject *ObjcToPyObject(id object) 
{ 
    if (object == nil) { 
     // This technically doesn't need to be an extra case, 
     // but you may want to differentiate it for error checking 
     return NULL; 
    } else if ([object isKindOfClass:[NSString class]]) { 
     return PyString_FromString([object UTF8String]); 
    } else if ([object isKindOfClass:[NSNumber class]]) { 
     // You could probably do some extra checking here if you need to 
     // with the -objCType method. 
     return PyLong_FromLong([object longValue]); 
    } else if ([object isKindOfClass:[NSArray class]]) { 
     // You may want to differentiate between NSArray (analagous to tuples) 
     // and NSMutableArray (analagous to lists) here. 
     Py_ssize_t i, len = [object count]; 
     PyObject *list = PyList_New(len); 
     for (i = 0; i < len; ++i) { 
      PyObject *item = ObjcToPyObject([object objectAtIndex:i]); 
      NSCAssert(item != NULL, @"Can't add NULL item to Python List"); 
      // Note that PyList_SetItem() "steals" the reference to the passed item. 
      // (i.e., you do not need to release it) 
      PyList_SetItem(list, i, item); 
     } 
     return list; 
    } else if ([object isKindOfClass:[NSDictionary class]]) { 
     PyObject *dict = PyDict_New(); 
     for (id key in object) { 
      PyObject *pyKey = ObjcToPyObject(key); 
      NSCAssert(pyKey != NULL, @"Can't add NULL key to Python Dictionary"); 
      PyObject *pyItem = ObjcToPyObject([object objectForKey:key]); 
      NSCAssert(pyItem != NULL, @"Can't add NULL item to Python Dictionary"); 
      PyDict_SetItem(dict, pyKey, pyItem); 
      Py_DECREF(pyKey); 
      Py_DECREF(pyItem); 
     } 
     return dict; 
    } else { 
     NSLog(@"ObjcToPyObject() could not convert Obj-C object to PyObject."); 
     return NULL; 
    } 
} 

您可能還需要看一看如果您還沒有,請致電Python/C API Reference manual

+0

謝謝Michael!在我發佈這個問題之前,我查看了C API,但是我無法弄清楚如何在Objective-C NS對象中使用PyDict方法(仍然從我的C上除塵;一直以來我都不得不考慮指針等等向前)。感謝您的入門代碼! – 2009-09-20 15:51:17