简体   繁体   English

使用Void *参数将套接字数据传递给JNA函数

[英]Pass Socket data to JNA Function with Void* Parameter

On Windows, I have some 3rd party TCP data coming in through a Java Socket, and I'm trying to figure out how to pass the data into a C Library provided by the same 3rd party - using JNA. 在Windows上,我有一些第三方TCP数据通过Java套接字传入,并且我试图弄清楚如何将数据传递给同一第三方提供的C库-使用JNA。 I am new to all things JNA/JNI/C etc. 我是JNA / JNI / C等所有事物的新手。

The 3rd Party library will take incoming bytes from the socket and decode them to the right message type. 第三方库将从套接字接收传入的字节,并将其解码为正确的消息类型。 Since the data coming in is of arbitrary length, has no end delimiter, and the start delimiter is very short (so could appear in the middle of the data and not be an actual delimiter) it's actually probably easier to figure out how to use this library though JNA instead of roll my own (or learn C). 由于传入的数据具有任意长度,没有结束定界符,并且起始定界符非常短(因此可能出现在数据中间,而不是实际的定界符),因此实际上可能更容易弄清楚如何使用此定界符库通过JNA而不是自己动手(或学习C)。

I've managed to use jnaerator to generate source code from the C header files. 我设法使用jnaerator从C头文件生成源代码。 I've also successfully called a simple C function requiring no parameters. 我还成功地调用了一个不需要参数的简单C函数。 However, when trying to use a function that requires passing "raw data" to a C function that originally accepted a void pointer, I'm not sure how to proceed. 但是,当尝试使用需要将“原始数据”传递给最初接受无效指针的C函数的函数时,我不确定如何进行。

Here are relevant snippets from the code. 以下是代码中的相关片段。

//CExportTypes.h
typedef unsigned int XUint;
//also defines structs: XMessageType, XCrypto, XAlarm, etc.

//CLibrary.h
XStatus XGetMessageType(void* bytesRecv, XUint numBytes, XMessageType* type, XUint* serial, XUint* msgLen);
XStatus XDecodeAlarm(void* bytesRecv, XUint numBytes, XCrypto* key, XAlarm* decodedAlarm);

//CLibrary.java (Generated)
int XGetMessageType(Pointer bytesRecv, int numBytes, IntBuffer type, IntBuffer serial, IntBuffer msgLen);
int XDecodeAlarm(Pointer bytesRecv, int numBytes, XCrypto key, XAlarm decodedAlarm);

How do I get the incoming 我如何收到

int = Socket.getInputStream()

"raw data" into a Pointer that the JNA function expects? 将“原始数据”放入JNA函数期望的指针? What other gotchas do I need to be aware of? 我还需要知道其他哪些陷阱? Endianness, unsigned byte issues, etc? 字节序,无符号字节问题等?

I know that may not be much to go on, but I appreciate any help I can get. 我知道可能不会继续做很多,但是我很感激我能得到的任何帮助。

Use a SocketChannel to read into a direct NIO buffer, which we can dereference from JNI. 使用SocketChannel读取直接的NIO缓冲区,我们可以从JNI中取消引用。 Something like: 就像是:

SocketChannel client = SocketChannel.open(address);
ByteBuffer buffer = ByteBuffer.allocate(42);
client.read(buffer);

And call your functions with Buffer as parameter instead of Pointer . 并使用Buffer作为参数而不是Pointer调用函数。

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

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