【问题标题】:How do we get String in Java(JNA), that returned by Python function using CFFI我们如何在 Java(JNA) 中获取由 Python 函数使用 CFFI 返回的字符串
【发布时间】:2020-12-10 18:06:29
【问题描述】:

在 CFFI 和 JNA 的帮助下,我编写了代码来使用 Java 中的 DLL 访问 Python 函数。 但是,我无法使用 CFFI 访问 Python 函数返回的字符串值低于错误。

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)**

此文件将生成 multiFilesWithSub.cmultiFilesWithSub5.dll。我使用 JNA 在 Java 中访问这个 DLL 来调用 python 函数 do_hello() 返回字符串 "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**

任何人都可以帮助从 cffi char* do_hello() 获取 Java 中的字符串吗?或者有什么办法可以得到 python函数在CFFI中返回字符串,然后在JAVA中?

【问题讨论】:

    标签: java python c jna python-cffi


    【解决方案1】:

    TypeError: ctype 'char[]' 的初始化程序必须是字节或列表或元组,而不是 str

    错误信息似乎很清楚:do_hello 必须返回“字节或列表或元组,而不是字符串”。要使函数返回bytes,您只需添加字母b:

    x = b"Hello World!"
    return x
    

    【讨论】:

      猜你喜欢
      • 2018-03-27
      • 2012-12-12
      • 2018-12-12
      • 2013-04-08
      • 2013-10-26
      • 2021-05-23
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多