无法在两个不同的类中使用外部 JNI 函数,未满足的链接错误
对于 Android 应用程序,我用 C 实现了一个外部函数,我想在两个单独的类中使用它。
在第一个类(我的主 Activity UI)中,我调用适当的 loadLibrary:
System.loadLibrary(...);
在同一个类中,我将函数定义为本机:
public native int dissectPacket(byte[] header, byte[] data, int encap);
执行此操作后,我可以在中调用本机函数没有问题第一堂课。我没有收到任何不满意的链接错误。
现在,我想在另一个类中使用这个函数。我想我不需要再次加载库。在第二个类的底部,我还定义了:
public native int dissectPacket(byte[] header, byte[] data, int encap);
但是,当我尝试在第二个类中使用本机函数时,我得到:
07-22 23:13:13.083: ERROR/AndroidRuntime(6737): Caused by: java.lang.UnsatisfiedLinkError: dissectPacket
在两个类中使用该函数的正确方法是什么?如果我不将函数重新定义为第二个类中的本机函数(称为 Packet),则会收到错误:
The method dissectPacket(byte[], byte[], int) is undefined for the type Packet
顺便说一句,我不想使用:class1.dissectPacket(...);我试图避免通过课程。
For an Android application, I have implemented an external function in C, which I would like to use in two separate classes.
In the first class (my main Activity UI), I call the appropriate loadLibrary:
System.loadLibrary(...);
In the same class, I define the function as native:
public native int dissectPacket(byte[] header, byte[] data, int encap);
After doing this, I can call the native function with no problem in the first class. I do not get any unsatisfied link error.
Now, I want to use this function in another class. I figure I do not need to load the library again. In the second class, at the bottom, I also define:
public native int dissectPacket(byte[] header, byte[] data, int encap);
However, when I try to use the native function in the second class, I get:
07-22 23:13:13.083: ERROR/AndroidRuntime(6737): Caused by: java.lang.UnsatisfiedLinkError: dissectPacket
What is the proper way to use the function in both classes? If I do not redefine the function as native in the second class (called Packet), I get the error:
The method dissectPacket(byte[], byte[], int) is undefined for the type Packet
BTW, I do NOT want to use: class1.dissectPacket(...); I am trying to avoid passing the class.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
您实际上定义了两个单独的函数。一个用于第一班,另一个用于第二班。他们将需要两个独立的 JNI 存根。您可能只有第一个的存根和实现。
一般来说,JNI 和 Java 总是引用特定类的方法。
You defined actually two separate functions. One for the first class and another one for the second. They will need two separate JNI stubs. You, probably, only have stub and implementation for the first one.
JNI and Java, in general, always refer to methods of the specific class.
“顺便说一句,我不想使用:class1.dissectPacket(...);我试图避免通过课程。”
如果你想这样做,成员函数必须是静态的,否则类将作为参数隐式传递(我不知道如何,因为我从未这样做过,静态函数一直对我有用,但它有才能正常工作)。
因此,将您的方法存根更改为:
"BTW, I do NOT want to use: class1.dissectPacket(...); I am trying to avoid passing the class."
If you want to do that, the member functions need to be static, otherwise the class is implicitly passed as a parameter (I don't know how because I've never done it, static functions have always worked for me, but it has to happen to work properly).
So change your method stubs to: