0

给定一个格式字符串和一个字典,都存储在PyObject*变量中,我如何使用这些值从 C API调用str.format_map ?

我的目标是做相当于:

# Given the "dict" and "fmt" are already in PyObject*
dict = {'Foo': 54.23345}
fmt = "Foo = {Foo:.3f}"

# How do I get result?
result = fmt.format_map(dict)
4

1 回答 1

1

像这个片段这样的东西就足够了:

PyObject *dict, *value, *result, *fmt;
dict = PyDict_New();
if (!dict)
     return NULL;
value = PyFloat_FromDouble(54.23345);
if (!value) {
     PY_DECREF(dict);
     return NULL;
}
if (PyDict_SetItemString(dict, "Foo", value) < 0) {
     Py_DECREF(value);
     Py_DECREF(dict);
     return NULL;
}
Py_DECREF(value);
fmt = PyUnicode_FromString("Foo = {Foo:.3f}");
if (!fmt) {
     Py_DECREF(dict);
     return NULL;
}
result = PyObject_CallMethodObjArgs(fmt, "format_map", dict, NULL);
Py_DECREF(fmt);
Py_DECREF(dict);
return result;

可以看到,这很麻烦,所以最好尽量用Python来做!

于 2013-08-22T00:59:25.227 回答