经过一番尝试,我可以看到:扩展执行与 dart 是异步的,但不是 C,它在当前方法尚未完成时阻塞。
Dart_NativeFunction ResolveName(Dart_Handle name, int argc);
Dart_Handle HandleError(Dart_Handle handle);
void wrapped_method(Dart_Port dest_port_id, Dart_CObject* message) {
Dart_Port reply_port_id = message->value.as_array.values[0]->value.as_send_port;
printf("Before sleep\n");
sleep(5);
printf("Hello from c !\n");
Dart_CObject result;
result.type = Dart_CObject_kBool;
result.value.as_bool = true;
Dart_PostCObject(reply_port_id, &result);
}
DART_EXPORT Dart_Handle sample_extension_Init(Dart_Handle parent_library) {
if (Dart_IsError(parent_library)) { return parent_library; }
Dart_Handle result_code = Dart_SetNativeResolver(parent_library, ResolveName);
if (Dart_IsError(result_code)) return result_code;
return Dart_Null();
}
void sample_extension_ServicePort(Dart_NativeArguments arguments) {
Dart_EnterScope();
Dart_SetReturnValue(arguments, Dart_Null());
Dart_Port service_port = Dart_NewNativePort("sample_extension_ServicePort", wrapped_method, true);
if (service_port != ILLEGAL_PORT) {
Dart_Handle send_port = HandleError(Dart_NewSendPort(service_port));
Dart_SetReturnValue(arguments, send_port);
}
Dart_ExitScope();
}
struct FunctionLookup {
const char* name;
Dart_NativeFunction function;
};
FunctionLookup function_list[] = {
{"SampleExtension_ServicePort", sample_extension_ServicePort},
{NULL, NULL}};
Dart_NativeFunction ResolveName(Dart_Handle name, int argc) {
if (!Dart_IsString(name)) return NULL;
Dart_NativeFunction result = NULL;
Dart_EnterScope();
const char* cname;
HandleError(Dart_StringToCString(name, &cname));
for (int i=0; function_list[i].name != NULL; ++i) {
if (strcmp(function_list[i].name, cname) == 0) {
result = function_list[i].function;
break;
}
}
Dart_ExitScope();
return result;
}
Dart_Handle HandleError(Dart_Handle handle) {
if (Dart_IsError(handle)) Dart_PropagateError(handle);
return handle;
}
当我执行 3 次调用服务端口的方法时:
Hello from Dart
Hello from Dart
Before sleep
Hello from Dart
Hello from c !
Before sleep
Hello from c !
Before sleep
Hello from c !
直到每个“来自 c 的你好!”,它的睡眠 5 秒。有一种方法在 C 端也是异步的吗?我见过 :
DART_EXPORT Dart_Port Dart_NewNativePort(const char* name,
Dart_NativeMessageHandler handler,
bool handle_concurrently);
伟大的 !但 ...
/* TODO(turnidge): Currently handle_concurrently is ignored. */
这有什么问题吗?(我想投票支持它以遵循解决方案)虽然问题没有解决,但最好的解决方案是什么?在 C fork 中运行代码?