I'm trying to build a python wrapper for gnucash c++ parts. In QofBackend I encountered the method const std::string && get_message ()
. This returns <Swig Object of type 'std::string *' at 0x7f4a20f5c9f0>
in my setting but I would like to access the string.
I didn't really find a simple explanation so I rebuilt an example setting and dug into c++ which I barely know. I managed to get the string into python but I'd like to know
- if this typemap(out) approach is correct (also in respect of memory and error handling).
- The conversion in
set_s_workaround()
is also just a workaround. I don't think that for gnucash the python code ever needs to set this value but for completeness sake it would be nice to also have atypemap(in) std::string&&
and - get rid of
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 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::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_s3('TEST')
s1.print_s()
print(s1.get_s())
Thanks for the help!
Aucun commentaire:
Enregistrer un commentaire