简体   繁体   English

JNI:本机库需要void *,如何将jbytearray转换为C void *

[英]JNI: Native library requires void*, how can I convert my jbytearray to C void*

Here is what I have so far: 这是我到目前为止的内容:

Java: Java:

public static native String getConfigName(byte[] array);

C: (the code below returns a dummy value for compilation) C :(下面的代码返回一个虚拟值进行编译)

jstring Java_com_example_plugin_HelloJni_getConfigName( JNIEnv* env, jobject thiz, jbyteArray array )
{

    // get jbyte array from array and it's length
    jbyte* bufferPtr = (*env)->GetByteArrayElements(env, array, NULL);
    jsize lengthOfArray = (*env)->GetArrayLength(env, array);

    // Code I need to run using void* and size_t
    dlpspec_scan_read_configuration (   void *  pBuf, const size_t  bufSize )

    // release array
    (*env)->ReleaseByteArrayElements(env, array, bufferPtr, 0);

    return (*env)->NewStringUTF(env, "Hello from JNI !  Compiled with ABI");
}

How can I convert this jbyte* to a void* would it be a simple (void*) cast? 如何将这个jbyte *转换为void *,这将是一个简单的(void *)强制转换? also what about the jsize to size_t conversion? 还有jsize到size_t的转换吗? this is my first time using JNI and the Android NDK. 这是我第一次使用JNI和Android NDK。 Thanks 谢谢

How can I convert this jbyte* to a void* would it be a simple (void*) cast? 如何将这个jbyte *转换为void *,这将是一个简单的(void *)强制转换?

Assuming that you want to pass the data it points to as-is, yes. 假设您要按原样传递数据,是的。 Or just pass your jbyte* to dlpspec_scan_read_configuration without any casting. 或者只是将您的jbyte*传递给dlpspec_scan_read_configuration而不进行任何强制转换。 Either way it's your responsibility to make sure that it's the correct type of data for dlpspec_scan_read_configuration (eg if your function expects a void* to an ASCII string but you pass it a void* to a Unicode string then you probably wouldn't get the desired result). 无论哪种方式,您dlpspec_scan_read_configuration责任确保它是dlpspec_scan_read_configuration的正确数据类型(例如,如果您的函数期望ASCII字符串为void* ,但您将NULL void*传递给Unicode字符串,则可能无法获得所需的数据)结果)。

what about the jsize to size_t conversion jsize到size_t的转换怎么样

jsize is an alias for jint , which is a signed 32-bit integer type. jsizejint的别名,它是一个有符号的32位整数类型。 size_t on the other hand is an unsigned integer type of unspecified size. 另一方面, size_t是未指定大小的无符号整数类型。 So you should check that your jsize is in the range 0..SIZE_MAX . 因此,您应该检查您的jsize是否在0..SIZE_MAX范围内。 If it is, you can cast it to a size_t . 如果是,则可以将其size_t转换为size_t If it isn't, it's up to you what you want to do (clamp the value, return an error, abort the program, ...). 如果不是,则取决于您要执行的操作(确定值,返回错误,中止程序等)。

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

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