你好,我刚学习native client,使用sdk里面的例子跑发现无法加载本地native 模块对象。自己按照你说的方法也写了一个demo,但是运行也是发现加载native module对象失败,该值为空。无法加载本地native模块对象。这是怎么回事呀?具体代码如下:
前端:
<!DOCTYPE html>
hello_tutorial
<br>
hello_tutorialModule = null; // 模块的全局对象<br>
statusText = 'NO-STATUS';</p>
<pre><code>// 更新状态
function moduleDidLoad() {
hello_tutorialModule = document.getElementById('hello_tutorial');
updateStatus('SUCCESS');
// 向模块发送消息
hello_tutorialModule.postMessage('hello');
}
// 消息句柄函数。句柄在NaCl模块发送相应消息时自动唤起。
// 在C中是PPB_Messaging.PostMessage(),C++中则是pp::Instance.PostMessage()
// 在这个demo当中,我们收到消息之后弹窗示意
function handleMessage(message_event) {
alert(message_event.data);
}
// 页面载入时很可能NaCl模块还没有载入,因此我们将状态写为正在读取;
// 而如果模块已经载入,则什么都不做。
function pageDidLoad() {
if (hello_tutorialModule == null) {
updateStatus('LOADING...');
} else {
// 事实上,NaCl模块的载入成功事件是不可能在页面载入成功事件之前就发生的,
// 因此我们这里简单的认为页面载入之后所更新显示的消息仍旧是当前消息,而不是'SUCCESS'。
updateStatus();
}
}
// 设置状态。如果存在id为'statusField'的元素,那么将其设置为参数携带的状态
function updateStatus(opt_message) {
if (opt_message)
statusText = opt_message;
var statusField = document.getElementById('status_field');
if (statusField) {
statusField.innerHTML = statusText;
}
}
</code></pre>
<p>
Native Client Module hello_tutorial
Status
native端:
/// @file hello_tutorial.cc
/// 载入NaCl模块时,浏览器首先将搜索CreateModule()方法,CreateModule()会返回一个对象实例,
/// 之后浏览器会调用该实例的CreateInstance()方法,这时浏览器每遇到一次相应的就会调用一次。
///
/// 浏览器通过Javascript的postMessage()函数与NaCl通信。
/// 当调用postMessage()时,浏览器会转而调用pp::Instance的HandleMessage()方法。
/// 而如果模块需要与外界主动通信,则是使用pp::Instance的postMessage()方法。
/// 注意,这两个postMessage()都是异步的,因此两者在调用之后迅速返回。
#include
#include
#include "ppapi/cpp/instance.h"
#include "ppapi/cpp/module.h"
#include "ppapi/cpp/var.h"
namespace {
// 这个字符串用来判断消息是否是我们期望的内容
const char* const kHelloString = "hello";
// 这个字符串用来向浏览器返回内容
const char* const kReplyString = "hello from NaCl";
} // namespace
/// 每一个NaCl模块都将有一个相应的pp::Instance子类实例对应,
/// 为了与浏览器进行通信,你必须重载 HandleMessage()方法以及PostMessage()方法
class hello_tutorialInstance : public pp::Instance {
public:
explicit hello_tutorialInstance(PP_Instance instance) : pp::Instance(instance)
{}
virtual ~hello_tutorialInstance() {}
/// HandleMessage() 负责接收浏览器中postMessage()发送的消息内容
/// 其中的参数几乎可以表示任何东西,但通常都是JSON字符串,比如这样:
/// var json_message = JSON.stringify({ "myMethod" : "3.14159" });
/// nacl_module.postMessage(json_message);
virtual void HandleMessage(const pp::Var& var_message) {
// 这里是处理消息的代码了
if (!var_message.is_string())
return;
std::string message = var_message.AsString();
pp::Var var_reply;
if (message == kHelloString) {
var_reply = pp::Var(kReplyString);
PostMessage(var_reply);
}
}
};
class hello_tutorialModule : public pp::Module {
public:
hello_tutorialModule() : pp::Module() {}
virtual ~hello_tutorialModule() {}
virtual pp::Instance* CreateInstance(PP_Instance instance) {
return new hello_tutorialInstance(instance);
}
};
namespace pp {
Module* CreateModule() {
return new hello_tutorialModule();
}
} // namespace pp