Skip to content

Embedding call function with args and kwargs #2207

@viewpointsa

Description

@viewpointsa

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

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions