SWIG c++ -> java 转换byte[] 的关键代码

这篇博客介绍了如何使用SWIG从Java的byte[]数组转换到C++的char数组,提供了一组输入typemaps,减少了内存复制和marshaling开销,适用于性能敏感的代码。示例和代码详细解释了转换过程。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

/*  
 * char *BYTE typemaps.  
 * These are input typemaps for mapping a Java byte[] array to a C char array. 
 * Note that as a Java array is used and thus passeed by reference, the C routine  
 * can return data to Java via the parameter. 
 * 
 * Example usage wrapping: 
 *   void foo(char *array); 
 *   
 * Java usage: 
 *   byte b[] = new byte[20]; 
 *   modulename.foo(b); 
 */ 
%typemap(jni) char *BYTE "jbyteArray" 
%typemap(jtype) char *BYTE "byte[]" 
%typemap(jstype) char *BYTE "byte[]" 
%typemap(in) char *BYTE { 
  $1 = (char *) JCALL2(GetByteArrayElements, jenv, $input, 0);  

 
%typemap(argout) char *BYTE { 
  JCALL3(ReleaseByteArrayElements, jenv, $input, (jbyte *) $1, 0);  

 
%typemap(javain) char *BYTE "$javainput" 
 
/* Prevent default freearg typemap from being used */ 
%typemap(freearg) char *BYTE "" 
 
 


/* 
 * unsigned char *NIOBUFFER typemaps. 
 * This is for mapping Java nio buffers to C char arrays.
 * It is useful for performance critical code as it reduces the memory copy an marshaling overhead.
 * Note: The Java buffer has to be allocated with allocateDirect.
 *
 * Example usage wrapping:
 *   %apply unsigned char *NIOBUFFER { unsigned char *buf };
 *   void foo(unsigned char *buf);
 *  
 * Java usage:
 *   java.nio.ByteBuffer b = ByteBuffer.allocateDirect(20); 
 *   modulename.foo(b);
 */
%typemap(jni) unsigned char *NIOBUFFER "jobject"  
%typemap(jtype) unsigned char *NIOBUFFER "java.nio.ByteBuffer"  
%typemap(jstype) unsigned char *NIOBUFFER "java.nio.ByteBuffer"  
%typemap(javain,
  pre="  assert $javainput.isDirect() : \"Buffer must be allocated direct.\";") unsigned char *NIOBUFFER "$javainput"
%typemap(javaout) unsigned char *NIOBUFFER {  
  return $jnicall;  
}  
%typemap(in) unsigned char *NIOBUFFER {  
  $1 = (unsigned char *) JCALL1(GetDirectBufferAddress, jenv, $input); 
  if ($1 == NULL) {  
    SWIG_JavaThrowException(jenv, SWIG_JavaRuntimeException, "Unable to get address of a java.nio.ByteBuffer direct byte buffer. Buffer must be a direct buffer and not a non-direct buffer.");  
  }  
}  
%typemap(memberin) unsigned char *NIOBUFFER {  
  if ($input) {  
    $1 = $input;  
  } else {  
    $1 = 0;  
  }  
}  
%typemap(freearg) unsigned char *NIOBUFFER ""  






%apply  char *BYTE {  char *buf };
%apply char *BYTE { char *data };
%apply unsigned char *NIOBUFFER { unsigned char *data};
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值