Xav*_*erB 3 c++ ffi dart flutter dart-ffi
我是新来的菲。但我成功地将 dart-ffi 与函数调用一起使用。
现在,我想在 dart ffi 中使用 C++ 对象。我不知道这是否可能,但我尝试过这样的。
构造函数调用的原型是:
function_dart = lib
.lookup<NativeFunction<function_native>>("constructor_function")
.asFunction();
Run Code Online (Sandbox Code Playgroud)
但我有 :
Failed to lookup symbol <constructor_function>,我尝试使用构造函数:
constructor_function
class::constructor_function
class::constructor_function(args)
Run Code Online (Sandbox Code Playgroud)
我做到了nm -gDC <lib>,我可以看到构造函数。
帮助 !
编辑1: @Botje,@Richard-Heap
我正在尝试使用 OpenCV 中的 VideoCapture 实例。
我已按照 Botje 的回答中的说明进行操作。
所以我创建了一个库,如下所示:
绑定.hpp:
#ifndef BIND_HPP
# define BIND_HPP
#include <opencv2/videoio.hpp>
extern "C" {
cv::VideoCapture *cvCreateVideoCapture(char *filename, int apiPreference);
}
#endif
Run Code Online (Sandbox Code Playgroud)
绑定.cpp:
#include "bind.hpp"
cv::VideoCapture *createVideoCapture(char *filename, int apiPreference) {
return new cv::VideoCapture(filename, apiPreference);
}
Run Code Online (Sandbox Code Playgroud)
我用来编译的命令:
g++ -c bind.cpp -lopencv -o bind.o
g++ bind.o -shared -o bind.so
Run Code Online (Sandbox Code Playgroud)
我得到:dart: symbol lookup error: ./lib/src/bind.so: undefined symbol: _ZN2cv12VideoCaptureC1ERKNSt7__cxx1112basic_stringIcSt11char_traitsIcESaIcEEEi
下一步是使用 VideoCapture 实例的方法。
谢谢
Dart ffi 使用 C 接口,因此您必须进行如下调整。
从 C++ 类开始
Rect::Rect(int32_t width, int32_t height) {
m_width = width;
m_height = height;
}
void Rect::setWidth(int32_t width) {
m_width = width;
}
void Rect::setHeight(int32_t height) {
m_height = height;
}
int32_t Rect::area() {
return m_width * m_height;
}
Run Code Online (Sandbox Code Playgroud)
创建 C 适配器头文件
EXTERNC void* rect_init(int32_t width, int32_t height);
EXTERNC void rect_destroy(void *ptr);
EXTERNC int32_t rect_area(void *ptr);
Run Code Online (Sandbox Code Playgroud)
和实施
void* rect_init(int32_t width, int32_t height){
return new Rect(width, height);
}
void rect_destroy(void *ptr){
auto typed_ptr = static_cast<Rect*>(ptr);
delete typed_ptr;
}
int32_t rect_area(void *ptr){
auto typed_ptr = static_cast<Rect*>(ptr);
return typed_ptr->area();
}
Run Code Online (Sandbox Code Playgroud)
在 Dart 中,创建 typedef
typedef example_init_rect = Pointer<Void> Function(Int32 w, Int32 h);
typedef ExampleInitRect = Pointer<Void> Function(int w, int h);
typedef example_free_rect = Void Function(Pointer<Void> p);
typedef ExampleFreeRect = void Function(Pointer<Void> p);
typedef example_area_rect = Int32 Function(Pointer<Void> p);
typedef ExampleAreaRect = int Function(Pointer<Void> p);
Run Code Online (Sandbox Code Playgroud)
并绑定C适配器函数。最后,您可以创建一个代理底层 C++ 类的 Dart 类。
class NativeRect {
Pointer<Void> _nativeInstance;
NativeRect(int width, int height) {
_nativeInstance = Example()._exInitRect(width, height);
}
void free() {
Example()._exFreeRect(_nativeInstance);
}
int get area => Example()._exAreaRect(_nativeInstance);
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
6712 次 |
| 最近记录: |