如何将C#对象传递到Xamarin中的JNI方法

本文关键字:Xamarin 中的 JNI 方法 对象 | 更新日期: 2023-09-27 18:20:37

我正在使用Xamarin,需要调用链接到的jar中的两个静态java方法

package com.test;
public class Car {
    public static Car makeCar(String name);
    public void drawCar(ImageView imageview);
}

我不知道如何将这两个方法的参数传递给JNI代码。JNIEnv.Call**Method()类使用一个JValue[]数组作为参数,我正试图用它来包装一个C#字符串,并像这样调用它:

// C#
string carName = "mustang";
JValue[] paramCarName = new JValue[] {
    new JValue(JNIEnv.NewString(carName))
};
IntPtr theClass = JNIEnv.FindClass("com.test.Car");
IntPtr theMethod = JNIEnv.GetMethodID(theClass, 
    "makeCar", "()Ljava/lang/String;");
IntPtr resultCar = JNIEnv.CallStaticObjectMethod(
    theClass, theMethod, paramCarName);

这是正确的用法吗?我在调用第二个方法时也遇到了同样的问题,它指的是android的ImageView:的C#版本

// C#
// Xamarin provides an ImageView wrapper class.
ImageView imageview = ...;
// Is it alright to use JNIEnv.ToJniHandle here to reference the imageview?
JValue[] paramCarName = new JValue[] {
    new JValue (JNIEnv.ToJniHandle (imageview))
};
...

上面的编译目前还可以,但我不能运行它,因为我只有免费版本。任何关于这方面的信息都会很好,因为我确信我滥用了这个。

感谢

如何将C#对象传递到Xamarin中的JNI方法

如果您在绑定jar时遇到问题,可以使用Transforms/Metadata.xml(此处为文档)修复错误。使用该文件,可以抑制导致代码生成问题的类或整个包的绑定。

如果Metadata.xml无法完成这项工作,另一个(不太理想的)选项是创建自己的Java库,该库封装了不会绑定的Java库并只公开您需要从C#访问的方法。然后把那个罐子捆起来。

但是,听起来你有Xamarin的免费版本(可能是你试图避免jar绑定的原因,因为这需要付费版本),所以我会尝试修复你的JNI代码:

// C#
IntPtr classHandle;
IntPtr theClass = JNIEnv.FindClass("com/test/Car", classHandle);
IntPtr theMethod = JNIEnv.GetMethodID(theClass, 
    "makeCar", "(Ljava/lang/String;)V");
// Just create a new JValue with your C# Android object peer
JNIEnv.CallStaticObjectMethod(classRef, methodRef, new JValue[] {
        new JValue(imageView)
    });

我的JNI不是超级高级的,所以请对以上内容持保留态度。但根据Xamarin Studio为jar绑定生成的代码,上述内容应该(接近)正确。