views:

41

answers:

2

C/C++ can use python API to load py.

But, only simple type is supported.

How can I pass map into py to be a dict with API?

Or, which methods are better?

+1  A: 

Use SWIG, which has some ready-made templates for various STL types. See this, for example.

Eli Bendersky
A: 

The Python C API supports C-level functionality (not C++ level one) -- basically, you can easily expose to Python things you could put in an extern C block (which doesn't include std::map &c) -- for other stuff, you need a bit more work. The nature of that work depends on what you're using to wrap your C++ code for Python consumption -- there are many options, including the bare C API, SWIG, SIP, Boost Python, Cython, ...

In the bare C API (which I assume is what you're using, judging from your question and tags), I would recommend making a custom object type -- maybe, these days, one subclassing collections.Mapping (MutableMapping if mutable, of course), as you would when implementing a mapping in Python -- and implementing the Mapping Object Structures plus the needed bits of a general type structure such as tp_iter and tp_iternext slots.

Of course, the key idea is that you'll implement item setting and getting, as well as iteration, by simply delegating to your chosen std::map and performing the needed type conversion and low-level fiddling (object allocation, reference counting) -- the latter is the part that higher-level frameworks for extending Python save you from having to do, essentially, but the "wrap and delegate" underlying architecture won't change by much.

Alex Martelli