Skip to content

log::error doesn't work in #[call_from_java()] methods #144

@iXanadu13

Description

@iXanadu13

workspace structure:

.
├──src
│   ├──lib.rs
│   └──main.rs
├──src-java
│   ├──src
│   │   └──main/java/com/github/ixanadu13/test
│   │        ├──util
│   │        │    └──Log.java
│   │        ├──HelloJNA.java
│   │        └──Main.java
│   │
│   ├──target
│   │   └──...
│   └──pom.xml
└──Cargo.toml

lib.rs:

use j4rs::prelude::*;
use j4rs_derive::*;
use j4rs::{ClasspathEntry, Instance, Jvm, JvmBuilder};

thread_local! {
    pub static JVM: Jvm = {
        let entry = ClasspathEntry::new("src-java/target/classes");
        let jvm = JvmBuilder::new()
            .classpath_entry(entry)
            .build()
            .expect("Failed to construct JVM");

        jvm
    };
}

#[call_from_java("com.github.ixanadu13.test.util.Log.error0")]
fn log_error(msg: Instance) {
    log::error!("it won't work.");
    JVM.with(|jvm| {
        let msg: String = jvm.to_rust(msg).unwrap();
        // also no output
        log::error!("[Java] Error: {}", msg);
        println!("println works");
    });
}

main.rs:

use j4rs::InvocationArg;

fn main() {
    env_logger::init();
    log::error!("it works");
    test_lib::JVM.with(|jvm| {
        jvm.invoke_static(
            "com.github.ixanadu13.test.HelloJNA", 
            "callNoArg", 
            InvocationArg::empty()
        ).unwrap();
    });
}

Log.java:

package com.github.ixanadu13.test.util;

import org.astonbitecode.j4rs.api.Instance;
import org.astonbitecode.j4rs.api.java2rust.Java2RustUtils;

public class Log {
    static {
        System.loadLibrary("test_lib");
    }

    public static void error(String msg){
        error0(Java2RustUtils.createInstance(msg));
    }
    private static native void error0(Instance<String> msg);
}

HelloJNA.java:

package com.github.ixanadu13.test;

import com.github.ixanadu13.test.util.Log;

public class HelloJNA {
    public static String hello(String name) {
        return "Hello, " + name;
    }
    public static void callNoArg() {
        Log.error("Test");
    }
}

Cargo.toml:

[package]
name = "jna_test"
version = "0.1.0"
edition = "2021"

[lib]
name = "test_lib"
crate-type = ["staticlib", "cdylib", "rlib"]

[dependencies]
j4rs = "0.21.0"
j4rs_derive = "0.1"
log = "0.4"
env_logger = "0.11.5"

output:

    Finished `dev` profile [unoptimized + debuginfo] target(s) in 0.27s
     Running `target\debug\jna_test.exe`
[2025-02-03T11:39:40Z ERROR jna_test] it works
println works

I upload it on Github: https://github.com/iXanadu13/jna_test

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions