【发布时间】: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.c 和 multiFilesWithSub5.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