简体   繁体   中英

Use c++ uint8_t * from c# using SWIG

I have a functiong which look somethink like this:

virtual int64_t Read(uint8_t* buffer, int64_t bufferLength) = 0

which we want to overide (as this is an abstract class) and implament from c# code (using director). using

%include "arrays_csharp.i"
%apply uint8_t INPUT[] {uint8_t* buffer}

I was able to get ac# translation with the signature of

public virtual long Read(byte[] buffer, long bufferLength)

which is what I wanted. but when trying to compile the SWIG code we are getting errors as follows:

 error C2440: '=': cannot convert from 'void *' to 'unsigned char *'
 note: Conversion from 'void*' to pointer to non-'void' requires an explicit cast

because of this lins in the generated swig cc file:

 int64_t c_result = SwigValueInit< int64_t >() ;
 long long jresult = 0 ;
 unsigned char* jbuffer = 0 ;
 long long jbufferLength  ;
 long long jbufferOffset  ;

 if (!swig_callbackRead__SWIG_0) {
    throw Swig::DirectorPureVirtualException("mip::Stream::Read");
  } else {
    jbuffer = (void *) buffer; <========= FAIL LINE
    jbufferLength = bufferLength;
    jresult = (long long) swig_callbackRead__SWIG_0(jbuffer, jbufferLength);
    c_result = (int64_t)jresult; 
  }

How can I tell SWIG not to cast to (void *)?

Looks like the directorin typemap isn't quite right here. I think this should be sufficient to fix it, on the line after your %apply directive:

%typemap(directorin) uint8_t *buffer "$input = $1;"

The above typemap only matches non-const uint8_t* parameters named buffer . We can make that much more generic if we want to, eg:

%typemap(directorin) SWIGTYPE * "$input = $1;"

Will match anything that doesn't have a better match, const or non-const alike. I can't figure out why that isn't the default anyway, so there's a risk here that it might break something elsewhere that I've not thought of, so you may prefer to continue being selective in where this gets applied..

You can also do something like:

%typemap(directorin) SWIGTYPE * "$input = ($1_ltype)$1;"

Or add another variant:

%typemap(directorin) const SWIGTYPE * "$input = const_cast<$1_ltype>($1);"

The error message from compiler is quite plain. You should explicitly convert void * to unsigned char * .

Try:

jresult = (long long) swig_callbackRead__SWIG_0(static_cast<unsigned char *>(jbuffer), jbufferLength);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM