[PyKDE] Re: How can I use SIP to wrap STL class?

Jim Bublitz jbublitz at nwinternet.com
Wed Apr 10 18:41:59 BST 2002


On 10-Apr-02 ejoy <ejoy at peoplemail.com.cn> wrote:
>I've read sip tutorial on internet and I know how to wrap a
> int foo(float);
> But I still have problem to wrap the following code snippet:
 
>#include <string>
>#include <vector>
> using namespace std;
> class A{
> public:
>       void foo(const vector<string>& input,vector<string>&
>                output);
> };
 
> I want to wrap it in this way:
> python:
 
> in = ['a','b','c']
> out = []
> A.foo(in,out)
> and the out should look like:['c','b','a'] 
 
> How can I do this using SIP.

The simplest way would be to used %MappedTypes. Also, if you have
control of the C++ code, it would be easier to do:

ListType foo (ListType)

in your class and then

out = foo (in)

in your Python code.

In either PyQt or PyKDE2, grep for %MappedType - there are a number
of examples that do the QList type, which would be very similar
(kprocesslist.sip is one example which is very similar). The
%MappedType construct provides two "methods" - one for converting
from Python to C++ and the other for converting C++ to Python. I'm
not that familiar with using the STL, but your %MappedType should
look something like:

%MappedType ListType
{
%HeaderCode
#include <some_stl_header_file.h> // for vector and string types ??
typedef std::vector<std::string> ListType; // this is probably close
                                           // but might not be
                                           //correct
%End

%ConvertFromTypeCode

<Code to convert from vector to a Python list here>

%End

%ConvertToTypeCode

<Code to convert from Python list to vector here>

%End
};

If you can't modify the C++ code to return a Python list, you will
need to write %MemberCode (following foo's declaration in the .sip
file) to accomplish that (I'm sure Phil will correct me if I'm
wrong). "ListType" can be any name you choose. "sipCpp" and
"sipCppPtr" in the PyQt/PyKDE2 examples are the pointers that
represent the data to and from C++ respectively - use those names.

Documentation for the required Python functions is in the "Python C
API" docs that usually come with a Python distribution.
Py_BuildValue (if you need it - probably won't in this example) is
documented in "Extending/Embedding Python" docs, also in a typical
distribution. The section in Mark Lutz' "Programming Python"
(O'Reilly) on embedding Python might also be helpful for examples of
passing values between Python and C/C++.

Jim





More information about the PyQt mailing list