How to transform C arguments (const uint8_t*, unsigned int size) into C# byte[] in SWIG

386 views Asked by At

I want achieve nice method signature with byte[] in CSharp for following c++ code

class BytesWriterStrategy
{
public:
    virtual void WriteBytes(const uint8_t* array, unsigned int size) = 0;
};
    
class Base64Strategy final : public BytesWriterStrategy
{
public:
    void WriteBytes(const uint8_t* array, unsigned int size) final;
};

I have typemaps for Java

%typemap(jstype) (const uint8_t *array, unsigned int size) "byte[]"
%typemap(jtype) (const uint8_t *array, unsigned int size) "byte[]"
%typemap(jni) (const uint8_t *array, unsigned int size) "jbyteArray"
%typemap(javadirectorin) (const uint8_t *array, unsigned int size) "$jniinput"
%typemap(javain) (const uint8_t *array, unsigned int size) "$javainput"
%typemap(in,numinputs=1) (const uint8_t *array, unsigned int size) {
  // Note the NULL here if you don't want to be making changes visible
  $1 = (uint8_t*) JCALL2(GetByteArrayElements, jenv, $input, NULL);
  $2 = JCALL1(GetArrayLength, jenv, $input);
}
%typemap(freearg) (const uint8_t *array, unsigned int size) {
  // Swap 0 for JNI_ABORT if you don't want to make changes visible
  JCALL3(ReleaseByteArrayElements, jenv, $input, (jbyte*)$1, 0); 
}
%typemap(directorin,descriptor="[B") (const uint8_t *array, unsigned int size) { 
  $input = JCALL1(NewByteArray, jenv, $2); 
  JCALL4(SetByteArrayRegion, jenv, $input, 0, $2, (jbyte*) $1); 
} 
%typemap(directorargout) (const uint8_t *array, unsigned int size) {
  (jenv)->GetByteArrayRegion($input, 0, $2, (jbyte*) $1); 
} 

Those typemaps transform c++ to java code that uses byte[] instead of SWIG pointers

public class BytesWriterStrategy {
...
  public void WriteBytes(byte[] array) {
    enrolmentJNI.BytesWriterStrategy_WriteBytes__SWIG_1(swigCPtr, this, Writer.getCPtr(writer), writer, name, array);
  }

  public BytesWriterStrategy() {
    this(enrolmentJNI.new_BytesWriterStrategy(), true);
    enrolmentJNI.BytesWriterStrategy_director_connect(this, swigCPtr, true, true);
  }
}
  
public class Base64Strategy extends BytesWriterStrategy {
...
  public void WriteBytes(byte[] array) {
    enrolmentJNI.Base64Strategy_WriteBytes__SWIG_1(swigCPtr, this, array);
  }
...
}

I am not able to figure out how to write typemaps for CSharp to have similar output as in Java.

0

There are 0 answers