如何使用 JNI 将 C 结构转移到 java?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/4656490/
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
How to transfer a C structure to java by use of JNI?
提问by Steffen Kuehn
From C I am creating a DLL which is loaded in Java. I call some C functions from java and also call Java functions from C (whith uncomplex data types) - this is working fine.
从 CI 正在创建一个以 Java 加载的 DLL。我从 java 调用了一些 C 函数,也从 C 调用了 Java 函数(带有不复杂的数据类型) - 这工作正常。
I struggle with the transfer of a C structure to Java.
我努力将 C 结构转移到 Java。
Here is a small example descriping what I want to do. It is not complete and maybe not correct because my problem is that I am not sure how to do it.
这是一个描述我想要做的事情的小例子。它不完整,可能不正确,因为我的问题是我不知道该怎么做。
My goal is to pass a structure from the type "StructType" from C to Java in order to use the values in the Java program.
我的目标是将“StructType”类型的结构从 C 传递到 Java,以便在 Java 程序中使用这些值。
In C
在 C
typedef struct {
unsigned char value1;
unsigned char value2;
} StructType;
void passStructToJava(StructType* myStruct)
{
class cls;
jmethodID mid;
/* GlobalEnv, GlobalObj are globlal values which are already set */
cls = (*GlobalEnv)->GetObjectClass(GlobalEnv, GlobalObj);
mid = (*GlobalEnv)->GetMethodID(GlobalEnv, cls, "receiveStructFromC", "(LPackage/StructType;)V");
(*GlobalEnv)->CallVoidMethod(GlobalEnv, GlobalObj, mid, myStruct);
}
In Java
在 Java 中
public class StructType {
public int value1; /* int because there is no uint8 type */
public int value2;
}
public StructType mMyStruct;
public StructType getMyStruct() {
return mMyStruct;
}
public void setMyStruct(StructType myStruct) {
mMyStruct = myStruct;
}
public void receiveStructFromC(StructType myStruct)
{
setMyStruct(myStruct);
}
Thanks in advance for your help.
Steffen
在此先感谢您的帮助。
史蒂芬
回答by dacwe
Check my post in this question: pass data between Java and C
检查我在这个问题中的帖子:在 Java 和 C 之间传递数据
回答by Vladimir Ivanov
I would suggest returning an int array, as far as your structure doesn't consist anything else.
我建议返回一个 int 数组,只要您的结构不包含任何其他内容。
As for returning the object: you can create an object of your StructType class, fill the values with setters and return it.
至于返回对象:您可以创建一个 StructType 类的对象,用 setter 填充值并返回它。
The necessary code samples can be found here.
可以在此处找到必要的代码示例。
Just the example, I haven't check this code.
只是示例,我还没有检查此代码。
returnObj = (*env)->AllocObject(env, objClass);
if (returnObj == 0) printf("NULL RETURNED in AllocObject()\n");
printf("Sizeof returnObj = %d\n", sizeof(returnObj) );
(*env)->SetObjectField (env, returnObj, fid5,
combinedEmployeeNameJava);
(*env)->SetIntField (env, returnObj, fid6, combinedSalary);