首先,我真的想说我不是 C 程序员,尤其是在涉及指针时,我什至没有假装我完全理解如何以最佳方式完成这类事情。
有了这个,这里是我的解决方案,基于在此处找到的原语示例: https ://github.com/dart-lang/samples/tree/master/ffi/primitives
原语.dart
import 'dart:ffi';
import 'dart:io' show Platform;
import 'package:ffi/ffi.dart';
typedef max_func = Int32 Function(Pointer<Int32> list, Int32 size);
typedef Max = int Function(Pointer<Int32> list, int size);
void main() {
var path = './primitives_library/libprimitives.so';
if (Platform.isMacOS) path = './primitives_library/libprimtives.dylib';
if (Platform.isWindows) path = r'primitives_library\Debug\primitives.dll';
final dylib = DynamicLibrary.open(path);
final list = [1, 5, 3, 59030, 131000, 0];
final listPtr = intListToArray(list);
final maxPointer = dylib.lookup<NativeFunction<max_func>>('max');
final max = maxPointer.asFunction<Max>();
print('${max(listPtr, list.length)}'); // 131000
malloc.free(listPtr);
}
Pointer<Int32> intListToArray(List<int> list) {
final ptr = malloc.allocate<Int32>(sizeOf<Int32>() * list.length);
for (var i = 0; i < list.length; i++) {
ptr.elementAt(i).value = list[i];
}
return ptr;
}
原语.h
int max(int *listPtr, int size);
原语.c
#include "primitives.h"
int max(int *listPtr, int size)
{
int currentMax = *listPtr;
for (int i = 0; i < size; i++)
{
if (currentMax < *listPtr)
{
currentMax = *listPtr;
}
listPtr++;
}
return currentMax;
}