调用使用dart FFI返回函数指针的C函数

w8ntj3qf  于 2022-12-30  发布在  其他
关注(0)|答案(1)|浏览(150)

我正在使用dart:ffi调用C函数。我有以下C代码

typedef void* (*unmanaged_callback_ptr)(const char* , const char*);
typedef char* (*managed_direct_method_ptr)(const char*, 
    const char* , unmanaged_callback_ptr);

使用函数指针作为返回类型或参数的如下方法

CPPLIB_API managed_direct_method_ptr CreateManagedDelegate(const char* libName, 
const char* type,
const char* methodName);

CPPLIB_API char* InvokeManagedFunction(const char* name,
 const char* args,
 unmanaged_callback_ptr unmanagedCallback);

问题是如何使用dart:ffi调用这些方法?我的意思是如何定义typedefs、查找方法以及在函数返回函数ptr时获取结果,即CreateManagedDelegate(..)返回managed_direct_method_ptr

wh6knrhe

wh6knrhe1#

最后我找到了问题的解决方案。下面是C++方法的typedefs

// typefefs for method 'CreateManagedDelegate' which returns managed_direct_method_ptr
typedef get_create_d = Pointer<NativeFunction<managed_direct_method>> Function(
    Pointer<Utf8>, Pointer<Utf8>, Pointer<Utf8>);
typedef getCreateD = Pointer<NativeFunction<managed_direct_method>> Function(
    Pointer<Utf8>, Pointer<Utf8>, Pointer<Utf8>);

// Typedefs of managed_direct_method
typedef managed_direct_method = Pointer<Utf8> Function(
    Pointer<Utf8>, Pointer<Utf8>, Pointer<NativeFunction<unmanaged_call_back>>);
typedef managedDirectMethodDart = Pointer<Utf8> Function(
    Pointer<Utf8>, Pointer<Utf8>, Pointer<NativeFunction<unmanaged_call_back>>);

// These are typedefs for actual function in C++ for which function ptr is defined
typedef unmanaged_call_back = Int32 Function(Pointer<Utf8>, Pointer<Utf8>);
typedef unmanagedCallBackDart = int Function(Pointer<Utf8>, Pointer<Utf8>);

现在如何使用这个typedefs来调用返回函数ptr的函数如下。我已经有了DLL的句柄dyLib

// Get create_d which returns managed_direct_method_ptr
getCreateD createD = dyLib
      .lookup<NativeFunction<get_create_d>>('CreateManagedDelegate')
      .asFunction();

..... // Assume that args to pass in method are defined as String<Utf8> 

Pointer<NativeFunction<managed_direct_method>> directMethodPtr =
      createD(managedLib, mType, methodName);

  managedDirectMethodDart directMethod = directMethodPtr.asFunction();

// Now call the function using function ptr 
Pointer<NativeFunction<unmanaged_call_back>> fptr =     
      bridgeLib.lookup('unmanagedCallback');

final outList = directMethod(methodName, ''.toNativeUtf8(), fptr).toDartString();

不返回函数指针,可以只返回一个bool作为状态,并在C++方法内部设置函数指针,该函数指针可以是类/结构的成员。
使用这种方法,你也可以避免所有以上的东西,使它更简单。因为这是为我工作,我标记为'已解决'

相关问题