在 Java 中使用 C++ 库
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/24608851/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Using C++ library in java
提问by satishsingh2230
I am new to this forum, so please excuse me if i cannot put my question in a right way.
我是这个论坛的新手,所以如果我不能以正确的方式提出我的问题,请原谅。
I want help in using a C++(.lib and.h)
files in java
.
I want to use methods of that .lib
file in my java code .
我想在使用帮助C++(.lib and.h)
文件中java
。
我想.lib
在我的 java 代码中使用该文件的方法。
Prototype of function is like :
函数原型如下:
FunctionXYZ(BYTE *Data1, BYTE *Data2, BYTE *Data3, int Data4);
Environment i would be using is centOS.
我将使用的环境是centOS。
Thank you in advance
先感谢您
P.S: I do not have source code for this .lib
PS:我没有这个 .lib 的源代码
采纳答案by maxdev
To use functions from a .lib
, you have to create JNI wrapper functionsfor these library functions, and then link them together with your library into a .dll
.
要使用 中的函数.lib
,您必须为这些库函数创建JNI 包装器函数,然后将它们与您的库链接到一个.dll
.
Example:
例子:
Assuming you have a function in your C++ library headers with this signature:
int example(int a, int b);
Create a function wrapper in C++:
JNIEXPORT jint JNICALL Java_MyClass_example (JNIEnv* env, jobject obj, jint a, jint b) { return (jint) example(a, b); }
Link the library and the wrapper into a DLL
Create a Java class with the native method:
public class MyClass { public native int example(int a, int b); }
Load the DLL using the
System.loadLibrary
function (or similar)- Now you can call the
example
method on an object ofMyClass
假设您的 C++ 库头文件中有一个带有此签名的函数:
int example(int a, int b);
在 C++ 中创建一个函数包装器:
JNIEXPORT jint JNICALL Java_MyClass_example (JNIEnv* env, jobject obj, jint a, jint b) { return (jint) example(a, b); }
将库和包装器链接到 DLL 中
使用本机方法创建一个 Java 类:
public class MyClass { public native int example(int a, int b); }
使用
System.loadLibrary
函数(或类似函数)加载 DLL- 现在你可以
example
在一个对象上调用该方法MyClass
回答by Yamen Ajjour
you can use JNI technology which enables you to interoperate with native code
您可以使用 JNI 技术,该技术使您能够与本机代码进行互操作
please refer to this http://www3.ntu.edu.sg/home/ehchua/programming/java/JavaNativeInterface.html
请参考这个 http://www3.ntu.edu.sg/home/ehchua/programming/java/JavaNativeInterface.html
回答by Confuto
Using JNI is probably the best way to go. Here is a Wikipedia link if you want to read up on it: http://en.wikipedia.org/wiki/Java_Native_Interface
使用 JNI 可能是最好的方法。如果你想阅读它,这里是一个维基百科链接:http: //en.wikipedia.org/wiki/Java_Native_Interface
And here is the documentation for it: http://docs.oracle.com/javase/7/docs/technotes/guides/jni/spec/jniTOC.html
这是它的文档:http: //docs.oracle.com/javase/7/docs/technotes/guides/jni/spec/jniTOC.html