Java Native Access不做C ++,对吧? [英] Java Native Access doesn't do C++, right?

查看:109
本文介绍了Java Native Access不做C ++,对吧?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我发现许多在线(包括一些关于stackoverflow)的参考资料用于JNA用于C ++库,但我在JNA文档中找不到的任何内容表明这是可能的。似乎没有任何方法可以包装C ++类,特别是。

I've found many references online (including some on stackoverflow) to JNA being used for C++ libraries, but nothing I can find in the JNA docs indicates that's possible. There doesn't seem to be any way to wrap a C++ class, in particular.

我需要本机访问才能使用RTAudio,但所有RTAudio的函数都是RTAudio类。所以只是为了确认,JNA不是正确的方法吗?

I need native access to use RTAudio, but all of RTAudio's functions are member functions of the RTAudio class. So just to confirm, JNA isn't the way to go right?

推荐答案

这个问题相当于问如何使用JNA调用C ++实例方法,它是可能,但你将不得不做一些工作。特别是,您需要编写一个包装器 externC s您实际需要调用的任何函数。

What this question amounts to is asking how to call C++ instance methods using JNA, and it's possible, but you're going to have to do some work. In particular, you'll need to write a wrapper which extern "C"s any functions you actually need to invoke.

对于任何类型* function()定义,您可以使用JNA将方法映射为返回 com.sun.jna.Pointer ,但是你将无法从JNA调用C ++对象上的方法。

For any arbitrary type* function() definition you can map the method using JNA as returning a com.sun.jna.Pointer, but you won't be able to invoke methods on a C++ object from JNA.

一个简单的解决方法是编写一个C接口只是为你调用对象上的方法的库...所以如果你有一些成员函数 foo()你可以从你的C ++代码中导出一个C方法:

A simple workaround for this would be to write a C interface library that simply invokes the method on the objects for you...so if you have some member function foo() you could export a C method from your C++ code:

extern "C" void bar(type* var){
   var->foo();
}

显然这会为你增加一些工作......但我怀疑是开销切换到 JNI 的情况大致相同。

Obviously this will add some work for you...but I suspect the overhead for switching to JNI would be about the same.

JNA只关心在DLL中导出方法的方式 - 而且必须是没有 C ++装饰(因此 externC),因此您可以在任何此类方法中执行任何操作,而不会暴露您调用的方法。

JNA only cares about the way in which the method is exported in the DLL -- and that must be without C++ decorations (hence the extern "C"), so you can do whatever you need to within any such method without exposing methods that you call.

在我上面的设计示例中,这意味着 foo(),只要它在DLL中定义即可实际上甚至不必暴露。由于它是一个C ++函数,JNA不能直接调用它,但它可以在JNA可以调用的函数内调用,这就是我提出的解决方案有效的原因。

In my contrived example above, this means that foo(), as long as it is defined within the DLL does not in fact have to even be exposed. Since it's a C++ function, JNA cannot call it directly, but it can be called from within a function that JNA can call, which is why my proposed solution works.

所以,是的,你可以在一个函数中完全封装对所有成员函数(创建,操作,销毁)的调用,JNA也不会关心。

So, yes, you can fully encapsulate calls to all the member functions (create, operate, destroy) in a single function and JNA won't care.

这篇关于Java Native Access不做C ++,对吧?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆