0

Python is calling a C++ function (wrapped using swig).

C++:

  std::wstring getFilePathMultiByte();

I can call this function in python. Question is how do I use this returned wstring? want to append filename to this path which gives error as shown in output below.

Python:

  path = getFilePathMultiByte()
  print path, type(path)
  file = path + "/Information.log"

Output:

_2012ad3900000000_p_std__wstring, type 'SwigPyObject'
TypeError: unsupported operand type(s) for +: 'SwigPyObject' and 'str'

How do I create a std::wstring in python? That may allow concatenation for me.

Thanks.

1
  • Use type(path) to see available methods for an object. Also, pprint.pprint(path) will show you the attributes. Commented Aug 1, 2012 at 20:15

1 Answer 1

2

The following example worked as intended with SWIG 2.0 on my machine:

%module test

%include "std_wstring.i"

%inline %{
  std::wstring foo() {
    return L"hi";
  }
%}

Which I then tested with:

Python 2.7.3rc2 (default, Apr 22 2012, 22:30:17)
[GCC 4.6.3] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> import test
>>> path = test.foo()
>>> print path, type(path)
hi <type 'unicode'>
>>> file = path + "/Information.log"
>>> print file
hi/Information.log
>>>

I'm not exactly sure what you've done wrong here - my guess would be you haven't got %include "std_wstring.i", but it's hard to say for certain given what you've shown.

Sign up to request clarification or add additional context in comments.

3 Comments

Thought I would get compile errors if proper includes are not present. I have %include "stl.i". Let me try this. BTW - What did type(path) print for you?
@sambha - the type was "<type 'unicode'>", but I'd marked it up wrongly in my original answer so it was being treated as HTML! As far as SWIG is concerned if it doesn't know enough about a type to wrap it properly it assumes the type is an opaque pointer and generates a wrapper accordingly.
Thanks. Adding %include "std_wstring.i" to the proper .i files solved it. Its unicode for me too. I have some chinese characters in the string so print is failing for other reasons. On to the next one. I had to edit <type aaa> in my question too.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.