I’m trying to register a native function through jni, and to do that, I have to store a pointer to the function in a jninativemethod struct, which has a void* field for the function pointer.
In setting that field, I get the error error: invalid conversion from void (*)(JNIEnv*, _jclass*, jlong, _jobject*)' to void* when compiling with GCC on unix.
I’ve looked around, and it seems you aren’t allowed to convert function pointers to void pointers, so is this interface just broken? Is there a ‘right’ way to do it? (other than using javah to generate headers and exporting the functions)
It’s true that casting a function pointer to a
void*is frowned upon in C++, because the standard declares it to be undefined behaviour.However, in the case of something like
RegisterNatives, there really is no alternative. Fortunately, the compilers you are likely to use with JNI are nice enough to make the cast behave as you would expect, despite the standard’s protests.For what it’s worth, the Visual C++ documentation for
voidexplicitly mentions that “A void pointer can point to a function”, so you’re in good shape on that point. Furthermore, the POSIX functiondlsymalso requires void-to-function casts to be legal, so it seems unlikely that GCC would trip you up here.You can also check the following two answers for more information about the legality and effectiveness of casting between void pointers and function pointers: