如何使用 swig 定义和传递 ByteBuffer?

2022-01-25 00:00:00 c swig java java-native-interface

我需要从 Java 调用 C 函数.该函数有以下API:

I need to call to C function from Java. The function has the following API:

void convert(char* pchInput, int inputSize, int convertValue, char* pchOutput, int* outputSize);

我正在使用 swig 来制作包装器.

I'm using swig in order to make the wrappers.

我读了这篇文章:ByteBuffer.allocate() 与 ByteBuffer.allocateDirect()

最好将结果 (pchOutput) 创建为 DirectByteBuffer.

And it seems best to create the result (pchOutput) as DirectByteBuffer.

  1. 如何将 Bytebuffer 传递给代码 c(使用 swig)
  2. c 代码如何从 ByteBuffer 读取和写入数据?
  1. How can I pass the Bytebuffer to the code c (using swig)
  2. How the c code will read and write the data from the ByteBuffer ?

谢谢

推荐答案

来自 http://swig.10945.n7.nabble.com/Re-How-to-specify-access-to-a-java-nio-ByteBuffer-td6696.html 应该在小的更改后工作(特别是 %typemap(in) (char* pchOutput, int* outputSize)) 因为我没有编译这个,只需运行 swig 来检查 java 端是否正确生成.

a little modified sample from http://swig.10945.n7.nabble.com/Re-How-to-specify-access-to-a-java-nio-ByteBuffer-td6696.html that should work after small changes (especially %typemap(in) (char* pchOutput, int* outputSize)) as I did not compiled this, just run swig to check if java side is properly generated.

%typemap(in)        (char* pchInput, int inputSize) {
  $1 = JCALL1(GetDirectBufferAddress, jenv, $input); 
  $2 = (int)JCALL1(GetDirectBufferCapacity, jenv, $input); 
} 
%typemap(in)        (char* pchOutput, int* outputSize) {
  $1 = JCALL1(GetDirectBufferAddress, jenv, $input); 
  $2 = &((int)JCALL1(GetDirectBufferCapacity, jenv, $input)); 
} 

/* These 3 typemaps tell SWIG what JNI and Java types to use */ 
%typemap(jni)       (char* pchInput, int inputSize), (char* pchOutput, int* outputSize) "jobject" 
%typemap(jtype)     (char* pchInput, int inputSize), (char* pchOutput, int* outputSize) "java.nio.ByteBuffer" 
%typemap(jstype)    (char* pchInput, int inputSize), (char* pchOutput, int* outputSize) "java.nio.ByteBuffer" 
%typemap(javain)    (char* pchInput, int inputSize), (char* pchOutput, int* outputSize) "$javainput" 
%typemap(javaout)   (char* pchInput, int inputSize), (char* pchOutput, int* outputSize) { 
    return $jnicall; 
} 

相关文章