简体   繁体   中英

SWIG, Python and unicode strings

I am developing a Python module using SWIG and linking with a certain library. I have a typemap like the following:

%typemap(in) MyStringType {
    char* buffer = 0;
    size_t size = 0;
    int alloc = SWIG_OLDOBJ;
    int res = SWIG_AsCharPtrAndSize( $input, &buffer, &size, &alloc );
    if (!SWIG_IsOK(res)) {
        SWIG_exception_fail(SWIG_TypeError, "in method '$symname', expecting string");
    }
    $1.p = buffer;
    $1.n = size - 1;
}

I have some function that takes as parameter MyStringType as the parameter:

void myFunc(MyStringType type);

Then, when I create the python module I do the following in python 2.7:

myFunc("Test string")

However, when I try with Python 3.4 I get the following:

 TypeError: in method 'myFunc', expecting string

I could solve that by adding this to the swig interface file:

%begin %{
#define SWIG_PYTHON_STRICT_UNICODE_WCHAR
%}

That solved the problem. However I still need to add one more macro because some other functions require it. So, now it is like this:

%begin %{
#define SWIG_PYTHON_STRICT_BYTE_CHAR
#define SWIG_PYTHON_STRICT_UNICODE_WCHAR
%}

This would make me call myFunc like this:

myFunc(b"Test string")

And everything works fine when using tox in my pc, for python 2.7, 3.4 and 3.5, but it fails in travis-ci. After removing the b before "Test string" it succeeds in travis-ci but fails in my pc. In travis-ci I have: python: 2.7.6, 3.4.3 In my pc : python: 2.7.13, 3.4.8

Any idea why?

Solved. Thanks for all the hints. It was different swig versions.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM