C / C ++反思与JNI - 用于调用本地code方法,该方法还没有被写入尚未 [英] C/C++ Reflection and JNI - A method for invoking native code which hasn't been written yet
问题描述
我采取了一块Java软件,希望能允许C库的插件。为了调用这些未来的职能,我需要以某种方式在Java中创建一个本地函数从中我可以调用code尚不存在。该方法签名将是静态的,但方法和类的名称可能会改变。
I am implementing a piece of Java software that will hopefully allow for C libraries as plugins. In order to call these future functions, I need to somehow create a native function in Java from which I can call the code that doesn't exist yet. The method signature will be static but the method and class names may change.
有没有一种方法来检查加载的库或可用的功能呢?我希望它的工作是结合的方式如下:
Is there a way to check the loaded libraries or available functions? The way I hope it would work would be as follows:
在我的Java类,我想有一个功能;
In my Java class I would have a function;
public static native void thirdParty(String class, String method, int[] data, int[] params);
这将调用一个函数在我的C库;
Which would call a function in my C library;
JNIEXPORT void JNICALL Java_com_ex_app_Native_thirdParty(JNIEnv *, jclass, jstring, jstring, jintArray, jintArray);
从中我可以采取的类和方法的名称,并呼吁他们,如果他们存在,如果他们不抛出异常。
From which I could take the class and method name and call them if they exist and throw an exception if they don't.
我想我要的是某种风格的Java反射但在C或做不到这一点C ++。
I guess what I'm looking for is some kind of Java style reflection but in C or failing that C++.
我怎样才能做到这一点?
How can I achieve this?
推荐答案
标准的方式(或普通,因为没有真正的标准)
The standard way (or common since there is no real standard)
是创建一个DLL(共享库)。
该DLL具有与返回一个指向工厂对象的固定名称为C的功能。
然后,您可以使用工厂来构建对象。
Is to create a DLL (shared lib).
That DLL has a "C" function with a a fixed name that returns a pointer to a factory object.
You can then use the factory to build objects.
例如:
DLL-> Wdigets1.dll C function -> extern "C" Fac& getWidgetFactory();
DLL-> BoilerWidget.dll C function -> extern "C" Fac& getWidgetFactory();
DLL-> RoundWidget.dll C function -> extern "C" Fac& getWidgetFactory();
因此,无论DLL在加载所有你需要做的就是一个函数指针getWidgetFactory(),现在你可以使用工厂来构建相应的部件。
Thus whatever dll you load all you need to do is get a pointer to the function getWidgetFactory() and now you can use the factory to build the appropriate widgets.
这背后的原因:
使您可以动态加载库的库也能让你找到的方法/函数的名字。但是,你需要使用的名称是全名。在C这是很好的界定。在C ++这是mangeled名称和跨编译器/平台等,所以便携code变化只能找到C的名字。
The reason behind this:
The libraries that allow you to load libraries dynamically also allow you to find methods/function by name. But the name you need to use is the full name. In "C" this is well defined. In "C++" this is the mangeled name and varies across compilers/platforms etc. So portable code can only find "C" names.
这篇关于C / C ++反思与JNI - 用于调用本地code方法,该方法还没有被写入尚未的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!