简体   繁体   中英

How do we get String in Java(JNA), that returned by Python function using CFFI

I have written code to access Python function using DLL in Java with th help of CFFI and JNA. However, I can't access String value returned by Python function using CFFI getting below error.

plugin.py

**import cffi
ffibuilder = cffi.FFI()
ffibuilder.embedding_api("""
   char* do_hello();   
""")
ffibuilder.set_source("multiFilesWithSub", "")
ffibuilder.embedding_init_code("""
from multiFilesWithSub import ffi

@ffi.def_extern()
def do_hello():
    print("Hello World!")
    x = "Hello World!"
    return x
    
""")
ffibuilder.compile(target="multiFilesWithSub5.*", verbose=True)**

This file will generate multiFilesWithSub.c and multiFilesWithSub5.dll . This DLL I am accessing in Java using JNA to call python function do_hello() which returns string "Hello World!" .

**public class PythonToJavaWithMultipleFiles {
public interface NativeInterface extends Library {
    public String do_hello();
}
 public static void main(String[] args) {
    ClassLoader loaderProp = Thread.currentThread().getContextClassLoader();
    URL urlPath = loaderProp.getResource("pythondll/multiFilesWithSub5.dll");
    System.out.println("urlPath:" + urlPath);
    System.out.println("getPath:" + urlPath.getPath());
    File file = new File(urlPath.getPath());
    System.out.println("file:" + file);
    String absolutePath = file.getAbsolutePath();
    NativeInterface simpleDll = Native.loadLibrary(absolutePath, NativeInterface.class);
    String strResult = simpleDll.do_hello();
    System.out.println("strResult:" + strResult);
 }

}**

O/P:

From cffi callback <function do_hello at 0x00000000194E9790>:
Traceback (most recent call last):
File "<init code for 'multiFilesWithSub'>", line 16, in do_hello
TypeError: initializer for ctype 'char[]' must be a bytes or list or tuple, not str
**strResult:null**

Can anyone help to get String in Java from from cffi char* do_hello()? or is there any way to get python function returned string in CFFI and then in JAVA?

TypeError: initializer for ctype 'char[]' must be a bytes or list or tuple, not str

The error message seems clear enough: do_hello has to return "bytes or list or tuple, not str." To make the function return bytes you just need to add the letter b:

x = b"Hello World!"
return x

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM