title: SWIG/C#: convert a std::vector<unsigned char> to byte[]
body: <p>How can I wrap all usages of a <code>std::vector&lt;unsigned char&gt;</code> in a C++ library with a <code>byte[]</code> in C# when using SWIG to generate the wrappers?</p>
  
  <p>I'm handling mostly binary data in my library and would like to avoid using the <code>std_vector.i</code> templates provided by SWIG, which create an implementation of <code>IList&lt;byte&gt;</code> that has to go through the PInvoke layer for accessing / modifying each element.</p>
  
  <p>I'd rather have the whole memory be copied to / from a native array whenever it gets passed in to or out of a method. Below are the typemaps I created for use in Java. How can this be done for C#?</p>
  
  <pre><code>%typemap(jni) std::vector&lt;unsigned char&gt; "jbyteArray"
  %typemap(jtype) std::vector&lt;unsigned char&gt; "byte[]"
  %typemap(jstype) std::vector&lt;unsigned char&gt; "byte[]"
  %typemap(javain) std::vector&lt;unsigned char&gt; "$javainput"
  %typemap(javaout) std::vector&lt;unsigned char&gt; { return $jnicall; }
  
  %typemap(in) std::vector&lt;unsigned char&gt; (std::vector&lt;unsigned char&gt; vec) {
    if (!$input) {
      SWIG_JavaThrowException(jenv, SWIG_JavaNullPointerException, "null array");
      return $null;
    }
    const jsize sz = jenv-&gt;GetArrayLength($input);
    jbyte* const jarr = jenv-&gt;GetByteArrayElements($input, 0);
    if (!jarr) return $null;
    vec.assign(jarr, jarr+sz);
    jenv-&gt;ReleaseByteArrayElements($input, jarr, JNI_ABORT);
    $1 = &amp;vec;
  }
  
  %typemap(out) std::vector&lt;unsigned char&gt; {
    const jsize sz = $1.size();
    $result = jenv-&gt;NewByteArray(sz);
    jenv-&gt;SetByteArrayRegion($result, 0, sz, reinterpret_cast&lt;signed char *&gt;($1.data()));
  }
  
  %apply std::vector&lt;unsigned char&gt; { const std::vector&lt;unsigned char&gt; &amp; };
  </code></pre>