哦,看起來像我誤解了你的問題。那麼,走向另一個方向並不是非常不同。這應該是(至少作爲一個開始)你正在尋找的功能(我沒有測試它徹底的,所以蟲子的提防):
// 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。
我有點驚訝,你不能只是通過PyObjC將NSDictionary傳遞到Python,然後把它像一個普通的Python字典。有沒有具體的東西沒有用? – bbum 2009-09-20 00:43:54
可能只是我的知識,如何做到這一點;關心如何使用PyObjC從Objective-C類中調用Python函數並將其傳遞給NSDictionary? PyObjC的C API文檔也很棒;看起來卻找不到任何東西。 – 2009-09-20 15:38:49
其實,沒有必要的代碼;我沒有注意到邁克爾已經在下面第二次回答我了!哎呦。 :-) – 2009-09-20 15:47:52