简体   繁体   English

使用SWIG从C#使用C ++ uint8_t *

[英]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). 我们要覆盖的内容(因为这是一个抽象类)和c#代码的实现(使用Director)。 using 运用

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

I was able to get ac# translation with the signature of 我可以使用以下签名进行ac#翻译

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: 但是,当尝试编译SWIG代码时,出现如下错误:

 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: 由于这个原因,在生成的swig cc文件中:

 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 *)? 如何告诉SWIG不要转换为(void *)?

Looks like the directorin typemap isn't quite right here. 似乎directorin型图在这里不太合适。 I think this should be sufficient to fix it, on the line after your %apply directive: 我认为这应该足以解决它,在%apply指令之后:

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

The above typemap only matches non-const uint8_t* parameters named buffer . 上面的类型映射仅匹配名为buffer非常量uint8_t*参数。 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. 将匹配没有更好匹配的任何东西,无论是const还是非const。 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 * . 您应该将void *显式转换为unsigned char *

Try: 尝试:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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