SWIG / C#:将std :: vector <unsigned char =“”>转换为byte []

时间:2018-06-17 20:41:05

标签: c# c++ swig

当使用SWIG生成包装器时,如何用C#中的std::vector<unsigned char>byte[]的所有用法包装在C ++库中?

我在我的库中主要处理二进制数据,并且希望避免使用SWIG提供的std_vector.i模板,这些模板创建了IList<byte>的实现,必须通过PInvoke层进行访问/修改每个元素。

每当将内存传入或传出方法时,我宁愿将整个内存复制到本机数组中。下面是我在Java中使用的创建的类型图。如何为C#做到这一点?

%typemap(jni) std::vector<unsigned char> "jbyteArray"
%typemap(jtype) std::vector<unsigned char> "byte[]"
%typemap(jstype) std::vector<unsigned char> "byte[]"
%typemap(javain) std::vector<unsigned char> "$javainput"
%typemap(javaout) std::vector<unsigned char> { return $jnicall; }

%typemap(in) std::vector<unsigned char> (std::vector<unsigned char> vec) {
  if (!$input) {
    SWIG_JavaThrowException(jenv, SWIG_JavaNullPointerException, "null array");
    return $null;
  }
  const jsize sz = jenv->GetArrayLength($input);
  jbyte* const jarr = jenv->GetByteArrayElements($input, 0);
  if (!jarr) return $null;
  vec.assign(jarr, jarr+sz);
  jenv->ReleaseByteArrayElements($input, jarr, JNI_ABORT);
  $1 = &vec;
}

%typemap(out) std::vector<unsigned char> {
  const jsize sz = $1.size();
  $result = jenv->NewByteArray(sz);
  jenv->SetByteArrayRegion($result, 0, sz, reinterpret_cast<signed char *>($1.data()));
}

%apply std::vector<unsigned char> { const std::vector<unsigned char> & };

0 个答案:

没有答案
相关问题