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 に答える