[英]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.在 CFFI 和 JNA 的帮助下,我编写了代码以在 Java 中使用 DLL 访问 Python function。 However, I can't access String value returned by Python function using CFFI getting below error.
但是,我无法使用 CFFI 获取以下错误来访问 Python function 返回的字符串值。
plugin.py插件.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 .该文件将生成multiFilesWithSub.c和multiFilesWithSub5.dll 。 This DLL I am accessing in Java using JNA to call python function do_hello() which returns string "Hello World!"
这个 DLL 我正在使用 JNA 在 Java 中访问以调用 python function 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**
Can anyone help to get String in Java from from cffi char* do_hello()?谁能帮助从 cffi char* do_hello() 获取 Java 中的字符串? or is there any way to get python function returned string in CFFI and then in JAVA?
或者有什么方法可以在 CFFI 和 JAVA 中获取 python function 返回的字符串?
TypeError: initializer for ctype 'char[]' must be a bytes or list or tuple, not str
TypeError: ctype 'char[]' 的初始值设定项必须是字节或列表或元组,而不是 str
The error message seems clear enough: do_hello
has to return "bytes or list or tuple, not str."错误信息似乎很清楚:
do_hello
必须返回“bytes or list or tuple,not str”。 To make the function return bytes
you just need to add the letter b:要使 function 返回
bytes
,您只需添加字母 b:
x = b"Hello World!"
return x
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.