How to pass two python dictionaries to C++ function received by map
I want to call a C++ function in Python that takes two Python dictionaries whose key values are lists, as parameters, like:
a = {'str1': [1, 2, 3], 'str2': [4, 5, 6]}
b = {'str3': [7, 8, 9], 'str4': [10, 11, 12]}
cppFunction(a, b)
And in C++, the function called take the two dictionaries and store them 开发者_开发知识库in two variables of the type map<string, vector<int>>
. How can I do this? Do I have to use boost library?
Thanks,
Qingkun
As I understand there are two parts to your question: 1. How to call a C++ function from python?, 2. What data structures should be used in C++ for holding the inputs for the computation?
An answer to 1. is a long story. See, for example, this question and this question. For 2., for the given example, I would either use map<string, vector<int>>
, as you have suggested, within a wrapper class, or multimap<string, int>
which would be quicker to use as its existing interface is likely to be useful more readily.
Update: Added link to an another answer for 1.
If you want to pass Python arguments to a C/C++ function that don't have direct C/C++ equivalents (i.e. aren't strings or numbers), the best you can do is get pointers to them as generic Python objects and treat them as such.
This means your C++ extension code will have to deal with them in generic terms just like the Python interpreter does, which entails doing things like looking up their methods and calling them to manipulate -- as in retrieve, set, or delete -- their contents if they're container objects, such as lists
, dicts
, and the like. Your extension can then use this information to build the specific C++ map<>
template type you want.
The open source PyCXX project provides facilities to make it easier to write C++ Python extensions in general, as well as providing pre-written C++ classes for handling Dict
and List
arguments. Better yet, you can treat them as abstract Sequence
and Mapping
objects which will make your extension code able to handle other Python types that implement the same interfaces.
精彩评论