简体   繁体   English

Java从DLL实例化C ++类

[英]Java instantiate C++ class from DLL

I wrote a set of C++ classes and created a DLL that exports one of these C++ classes. 我编写了一组C ++类并创建了一个导出这些C ++类之一的DLL。 I need to instantiate the exported C++ class in a Java class. 我需要在Java类中实例化导出的C ++类。 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. 我在网上搜索了一个可能的解决方案,但我发现只有使用JNA或JNI的解决方案才能导入C ++ 函数

Yes, you can instantiate a C++ class from Java. 是的,您可以从Java实例化C ++类。

One way is with SWIG , which can generate Java wrappers for C++ classes. 一种方法是使用SWIG ,它可以为C ++类生成Java包装器。

For example, given a C++ class like this: 例如,给定一个像这样的C ++类:

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

SWIG allows you to write Java code like this: SWIG允许您编写如下Java代码:

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. 如果要从Java实例化C ++类,则必须编写一些实例化所需对象的粘合代码(在C ++中)。 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). 此外,您需要一个与C ++类相对应的Java类,并且需要使用粘合代码将C ++对象转换为上述Java类的对象,并将它们保持在一起(即,应该对C ++对象进行更改)反思到Java对象,反之亦然)。

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. 具体来说,它告诉您如何实例化Java对象,这是上述方法所需要的。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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