pybind11 icon indicating copy to clipboard operation
pybind11 copied to clipboard

Embedding call function with args and kwargs

Open viewpointsa opened this issue 6 years ago • 1 comments

Hello,

I'm embedding python into C++, and I want to call function with args, and kwargs :

PyObject* pyJsonModule = PyImport_ImportModule("json");
PyObject* pyJsonDic = PyModule_GetDict(pyJsonModule); 
PyObject* pyLoadsFct = PyDict_GetItemString(pyJsonDic, "dumps");
PyObject *args = Py_BuildValue("(O)", (const PyObject*)o);
PyObject *keywords = PyDict_New();
PyDict_SetItemString(keywords, "indent", PyLong_FromLong(4) );
PyDict_SetItemString(keywords, "sort_keys", Py_True );
PyDict_SetItemString(keywords, "ensure_ascii", Py_False );
PyObject* pyObject = PyObject_Call( pyLoadsFct, args, keywords );

How to translate that to pybind ?

py::module json = py::module::import("json");
py::dict args( "indent"_a=4, "sort_keys"_a=py::cast(true), "ensure_ascii"_a=py::cast(false) );
py::kwargs kwargs(args);
auto ret = json.attr("dumps")(o,kwargs); // ?

ps: thanks for this amazing python binder

viewpointsa avatar May 12 '20 10:05 viewpointsa

Ok I found :

	py::module json = py::module::import("json");
	auto dumps = json.attr("dumps");
	auto ret = dumps( o, "indent"_a=4, "sort_keys"_a=py::cast(true), "ensure_ascii"_a=py::cast(false)  );

viewpointsa avatar May 12 '20 13:05 viewpointsa