Hi,
Is it possible to use a C++ code/objects in an SNI C function?
If so, could you please point me to any documentation or an example that shows how to use it?
Thanks
Hi,
Is it possible to use a C++ code/objects in an SNI C function?
If so, could you please point me to any documentation or an example that shows how to use it?
Thanks
Hi,
Yes, you can call C++ functions or use C++ objects from an SNI C function.
To do that, in your C++ source file, you need to surround the SNI function definition with the extern "C" { ... }
directive.
It is worth noting the C++ objects fields and methods cannot be accessed directly from the Java code.
In Java, you can retrieve, store, and use a reference to a C++ object using pointers. These pointers must be stored as Java long
fields.
Here is an example of a Java code that declares native methods that use C++ objects:
public class TestCPP {
public static void main(String[] args) {
long cppObject = newCppObject();
cppPrintHelloWorld(cppObject);
}
/**
* Allocates and returns a C++ object.
*/
public static native long newCppObject();
/**
* Calls a C++ object's method.
*/
public static native void cppPrintHelloWorld(long cppObject);
}
And the C++ code that defines a C++ class and the SNI wrappers to access it:
CppObject::CppObject() {
}
void CppObject::printHelloWorld() {
std::cout << "Hello world C++"<<std::endl;
}
/* Implement here the SNI wrapper functions to call C++ object's methods*/
#ifdef __cplusplus
extern "C" {
#endif
int64_t Java_com_mycompany_TestCPP_newCppObject() {
void *cppObjectPtr = new CppObject();
return (int64_t)cppObjectPtr;
}
void Java_com_mycompany_TestCPP_cppPrintHelloWorld(int64_t cppObjectPtr) {
CppObject* cppObject = static_cast<HelloWorld *>((void*)cppObjectPtr);
cppObject->printHelloWorld();
}
#ifdef __cplusplus
}
#endif
Regards,
Jerome