2012-10-23 13 views
8

Próbuję przekonwertować funkcję C++ z std::string odniesienia do C#.Jak SWIG std :: string & do C# ref string

Moje API wygląda następująco:

void GetStringDemo(std::string& str); 

Idealnie chciałbym zobaczyć coś takiego od C#

void GetStringDemoWrap(ref string); 

Rozumiem, że muszę stworzyć typemap do tego, a ja próbowałem kilka rzeczy, bawiąc się plikiem std_string.i, ale nie sądzę, żebym nigdzie się nie dostał. Czy ktoś ma jakiś przykład. Jestem nowy w Swig i C#, więc nie jestem w stanie wymyślić żadnych prawdziwych pomysłów.

Odpowiedz

5

Na wypadek, gdyby ktoś szukał tego w przyszłości, stworzyłem std_string.i w ten sposób dla C#. Wydaje się, że pracujesz dla mnie. Zauważ, że zmieniłem ref do out, ponieważ było to bardziej odpowiednie w moim przypadku, ale powinno również zadziałać.

Zadzwoniłem% to "std_string.i" pliku .i

/* ----------------------------------------------------------------------------- 
* std_string_ref.i 
* 
* Typemaps for std::string& and const std::string& 
* These are mapped to a C# String and are passed around by reference 
* 
* ----------------------------------------------------------------------------- */ 

%{ 
#include <string> 
%} 

namespace std { 

%naturalvar string; 

class string; 

// string & 

%typemap(ctype) std::string & "char**" 
%typemap(imtype) std::string & "/*imtype*/ out string" 
%typemap(cstype) std::string & "/*cstype*/ out string" 

//C++ 
%typemap(in, canthrow=1) std::string & 
%{ //typemap in 
    std::string temp; 
    $1 = &temp; 
%} 

//C++ 
%typemap(argout) std::string & 
%{ 
    //Typemap argout in c++ file. 
    //This will convert c++ string to c# string 
    *$input = SWIG_csharp_string_callback($1->c_str()); 
%} 

%typemap(argout) const std::string & 
%{ 
    //argout typemap for const std::string& 
%} 

%typemap(csin) std::string & "out $csinput" 

%typemap(throws, canthrow=1) string & 
%{ SWIG_CSharpSetPendingException(SWIG_CSharpApplicationException, $1.c_str()); 
    return $null; %} 

} 

Powodem muszę zdefiniować argout dla const std :: string & dlatego SWIG będą się mylić i zastąpić const std: : string & również z typemap. Więc wyraźnie powiedzieć to nie do zastąpienia w moim przypadku (może mieć inny przypadek użycia)

dla Pythona stworzyłem coś takiego:

%typemap(argout)std::string& 
{ 
    //typemap argout std::string& 
    PyObject* obj = PyUnicode_FromStringAndSize((*$1).c_str(),(*$1).length()); 

    $result=SWIG_Python_AppendOutput($result, obj); 
} 

%typemap(argout) const std::string & 
%{ 
    //argout typemap for const std::string& 
%}