2

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)

Bwmat
  • 4,314
  • 3
  • 27
  • 42
  • Are you casting your function pointers to `void*`, or just trying to assign them directly? Direct assignment won't work, but a `reinterpret_cast` should do the trick. – Stuart Cook Sep 24 '11 at 15:14
  • explicitly casting to void* does shut the compiler up, I'm just worried that it will break on some platform since it's not allowed by the C++ standard. – Bwmat Sep 26 '11 at 18:04

1 Answers1

4

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 void explicitly mentions that “A void pointer can point to a function”, so you're in good shape on that point. Furthermore, the POSIX function dlsym also 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:

Community
  • 1
  • 1
Stuart Cook
  • 3,994
  • 25
  • 23