1

Suppose I have the following C++ function:

int summap(const map<int,int>& m) {
    ...
}

I try to call it from Python using cppyy, by sending a dict:

import cppyy
cppyy.include("functions.hpp")
print(cppyy.gbl.summap({55:1,66:2,77:3}))

I get an error:

TypeError: int ::summap(const map<int,int>& v) =>
    TypeError: could not convert argument 1

How can I call this function?

Erel Segal-Halevi
  • 33,955
  • 36
  • 114
  • 183

1 Answers1

1

There is no relation between Python's dict and C++'s std::map (the two have completely different internal structure), so this requires a conversion, there is currently no automatic one in cppyy, so do something like this:

cppm = cppyy.gbl.std.map[int, int]()
for key, value in {55:1,66:2,77:3}.items():
    cppm[key] = value

then pass cppm to summap.

Automatic support for python list/tuple -> std::vector is available, but there, too, it's no smarter than copying (likewise, b/c the internal structure is completely different), so any automatic std::map <-> python dict conversion would internally still have to do a copy like the above.

Wim Lavrijsen
  • 3,453
  • 1
  • 9
  • 21