Can you swig enhance: optionally <>?

I have successfully used SWIG to create a shell interface so that C ++ libraries are available in C #. I recently exposed some objects boost::optional<>, and SWIG had problems with them. Is there a standard way to handle this? Someone had to face this before ...

+5
source share
2 answers

Because SWIG does not understand boost types, type characters must be written. Here are a couple of typemaps for boost::optional<int>.

From Python, Noneor an integer can be passed to a function:

%typemap(in) boost::optional<int> %{
    if($input == Py_None)
        $1 = boost::optional<int>();
    else
        $1 = boost::optional<int>(PyLong_AsLong($input));
%}

boost::optional<int> None Python:

%typemap(out) boost::optional<int> %{
    if($1)
        $result = PyLong_FromLong(*$1);
    else
    {
        $result = Py_None;
        Py_INCREF(Py_None);
    }
%}
+3

# std::vector

#if SWIGCSHARP

// C++
%typemap(ctype) boost::optional<int32_t> "void *"
%typemap(out) boost::optional<int32_t> %{

    std::vector<int32_t> result_vec;
    if (!!$1)
    {
        result_vec = std::vector<int32_t>(1, $1.get());
    }
    else
    {
        result_vec = std::vector<int32_t>();
    }

    $result = new std::vector< uint32_t >((const std::vector< uint32_t > &)result_vec); 
%}

// C#
%typemap(imtype) boost::optional<int32_t> "global::System.IntPtr"
%typemap(cstype) boost::optional<int32_t> "int?"
%typemap(csout, excode=SWIGEXCODE) boost::optional<int32_t> {
    SWIG_IntVector ret =  new SWIG_IntVector($imcall, true);$excode

    if (ret.Count > 1) {
        throw new System.Exception("Return vector contains more then one element");
    }
    else if (ret.Count == 1) { 
        return ret[0]; 
    }
    else { 
        return null; 
    }
}

#endif //SWIGCSHARP
0

All Articles