xiongyihui / notes

Notes
https://xiongyihui.github.io/notes/
3 stars 0 forks source link

Python TypeError of std::string & #1

Open xiongyihui opened 7 years ago

xiongyihui commented 7 years ago

When using swig to wrap c++ code void test(std::string &s, I got the error TypeError: in method 'test', argument 1 of type 'std::string &'

It seems std::string & must be used together with const. We should use void test(const std::string &s) instead.

Example code

// example.cc
#include <iostream>
#include <string>

void test(const std::string &s)
{
    std::cout << s << std::endl;
}
// example.h
#ifndef __EXAMPLE_H__
#define __EXAMPLE_H__

#include <string>

void test(const std::string &s);

#endif // __EXAMPLE_H__
// example.i
%module example
%include std_string.i

%{
#include "example.h"
%}

%include "example.h"

Compile

swig -c++ -python -o example-swig.cc example.i
g++ -shared -fPIC `python-config --cflags --ldflags` -o _example.so example-swig.cc example.cc

Test

python
>>import example
>>example.test('hello, world')