简体   繁体   中英

Java instantiate C++ class from DLL

I wrote a set of C++ classes and created a DLL that exports one of these C++ classes. I need to instantiate the exported C++ class in a Java class. Is that possible?

I searched the web for a possible solution, but all I have found where solutions using JNA or JNI that import C++ functions only.

Yes, you can instantiate a C++ class from Java.

One way is with SWIG , which can generate Java wrappers for C++ classes.

For example, given a C++ class like this:

class MyClass { 
public:
     MyClass();
     int myMethod( int arg );
}

SWIG allows you to write Java code like this:

MyClass myclass = new MyClass();
int val = myClass.myMethod( 42 );

If you want to instantiate a C++ class from Java, you'll have to write a little glue code (in C++) that instantiates the desired object. Further, you'll need a Java class that corresponds to the C++ class, and you need to have the glue code convert the C++ object into an object of the Java class aforementioned, and keeps them together (ie, changes to the C++ object should reflect to the Java object, and the other way around).

This tutorial seems to have some pointers how you could do that. Specifically, it tells you how to instantiate a Java object, which is what you will need for the above approach.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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