问题描述
我目前需要在Flutter项目中为Linux桌面应用程序调用C ++函数(使用dart:ffi)。本页https://flutter.dev/docs/development/platform-integration/c-interop#first-party-library没有解释如何在Linux上配置此类项目(对于Windows均不适用)。
尝试几次后,我无法正确链接C ++库。
C ++函数
#include<iostream>
extern "C" {
void do_something(const char *program_name,const char *password)
{
//Do something with data
}
}
我在CMakeLists.txt中添加了以下几行:
add_library(my_native STATIC ../native_lib/my_native.cpp)
target_link_libraries(${BINARY_NAME} PUBLIC my_native)
最后,我将通过以下方式链接Dart:
// Since the CMake code was added in the executable CMakeLists.txt,it seems that it
// is supposed to be done that way,with DynamicLibrary.executable() rather than DynamicLibrary.process()
// method
final DynamicLibrary lib = DynamicLibrary.executable();
final doSomethingFuncPointer = lib.lookup<NativeFunction<do_something_signature>>("do_something");
它可以正常编译,但是在启动时,程序返回以下错误:
[ERROR:Flutter/lib/ui/ui_dart_state.cc(171)] Unhandled Exception: Invalid argument(s): Failed to lookup symbol (/home/me/Documents/Flutter/desktop_installer_framework/build/linux/debug/bundle/installer: undefined symbol: do_something)
我还尝试了动态链接(在CMakeLists.txt中将库标记为SHARED
,并将其与DynamicLibrary.open("libmy_native.so")
链接)。还尝试调用DynamicLibrary.process()
并将CMake行放入第二个CMakeLists.txt(Linux / Flutter中的那个)。它永远找不到符号。所以,我想我在这里错过了一些东西。
任何帮助将不胜感激。
最好的问候
解决方法
您已经显示了定义;那也是宣言吗?如果是这样(由于您那里有extern
,这似乎很可能),您将丢失链接到的页面描述的需要C ++的visibilty
和used
批注,这将解释为什么该符号不在生成的二进制文件中。