Wednesday, November 14, 2018

Mixing C++ and C and calling a C/C++ dll from Java

In Visual Studio, it is possible to mix C++ and C code, C++ files should have cpp extension, C files should have C extension, the compiler takes care of the rest. When including a C header file inside a C++ file, wrap it inside extern "C { #include "somfile.h"}. Otherwise, you will get LNK2019 (the dreaded "unresolved external symbol" error).

When you want to create a dll from this mixed project to be used with Java, in your wrapper header file of cpp implementation, you have to wrap the header body inside #ifdef __cplusplus extern "C" { #endif ...  #ifdef __cplusplus } #endif. Otherwise you will be able load the dll in Java but when you call a dll method, you will get UnsatisfiedLinkError.

When naming your functions in C/C++ Java interface functions section, do not use underscores at the end of the function name like "Java_package_name_myFunction_rad_s()" because in Java interface functions, undescores are only used as package name separators. If you ignore this, you will get UnsatisfiedLinkError and wonder why.

No comments: