我正在尝试为gnucash c ++部件构建python包装器。在QofBackend中,我遇到了方法const std::string && get_message ()
。在python中,此消息返回<Swig Object of type 'std::string *' at 0x7f4a20f5c9f0>
而不是如我的设置中的字符串,因为没有为此的swig typemap。
我并没有真正找到一个简单的解释,所以我重建了一个示例设置,并将其挖掘为几乎不知道的c ++。我设法将字符串放入python中,但我想知道
set_s_workaround()
中的转换也是一种解决方法。我不认为gnucash的python代码曾经需要设置此值,但是出于完整性的考虑,最好还有typemap(in) std::string&&
和get_s_workaround
。/* example.hpp */ #include <string> using namespace std; struct struct1{ string s; const std::string&& get_s(); void set_s(string&&); void set_s_workaround(string); void init_s(); void init_s_2(); void print_s(); }; string conv_rvalue_string(string);
/* example.cpp */ #include<iostream> #include"example.hpp" using namespace std; void struct1::set_s (std::string&& msg) { s = msg; } std::string conv_rvalue_string (std::string msg) { return msg; } void struct1::set_s_workaround(std::string msg) { set_s ( conv_rvalue_string(msg) ); } void struct1::init_s () { set_s("Some content"); } void struct1::init_s_2() { std::string msg {"Couldn't find "}; /* set_s( msg ); */ } void struct1::print_s () { cout<<get_s()<<endl; } const std::string&& struct1::get_s () { return std::move(s); }
/* example.i */ %module example %include "std_string.i" %typemap(out) std::string&& { std::string s = *$1; $result = SWIG_From_std_string(s); } %{ #include <string> #include "example.hpp" %} %include "example.hpp"
#!/bin/bash swig3.0 -c++ -shadow -python example.i g++ -fpic -c example.hpp example.cpp example_wrap.cxx -I/usr/include/python3.7 g++ -shared example_wrap.o example.o -o _example.so
# example.py import example s1 = example.struct1() s1.set_s_workaround('TEST') s1.print_s() print(s1.get_s())
感谢您的帮助!
我正在尝试为gnucash c ++部件构建python包装器。在QofBackend中,我遇到了const std :: string && get_message()方法。在python中,此消息返回
init_s2()将像这样工作: