我们如何在java(jna)中获得python函数使用cffi返回的字符串

5jvtdoz2  于 2021-07-08  发布在  Java
关注(0)|答案(1)|浏览(284)

在cffi和jna的帮助下,我编写了在java中使用dll访问python函数的代码。但是,我无法使用cffi get below error访问python函数返回的字符串值。
插件.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.c和multifileswithsub5.dll。我正在java中访问这个dll,使用jna调用python函数do\u 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);
 }

}**
订单号:

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中呢?

ruarlubt

ruarlubt1#

typeerror:ctype“char[]”的初始值设定项必须是字节、列表或元组,而不是str
错误信息似乎很清楚: do_hello 必须返回“bytes或list或tuple,not str.”才能使函数返回 bytes 你只需要加上字母b:

x = b"Hello World!"
return x

相关问题