实例
本例将创建一个名为LJFrontPanel的类以及类的实例ljfrontpanel,这个类提供了一个方法writeLed(const String&),方法中只有简单的操作,作为示例而已。将下面创建的LJFrontPanel.h、LJFrontPanel.cpp和LJFrontPanel.idl放到WebCore/page下。
LJFrontPanel.h
点击(此处)折叠或打开
- #ifndef LJFrontPanel_H
- #define LJFrontPanel_H
- #include <wtf/PassRefPtr.h>
- #include <wtf/RefCounted.h>
- #include <stdio.h>
- #include <string.h>
- #include "CString.h"
- #include "PlatformString.h"
- namespace WebCore {
- class LJFrontPanel : public RefCounted<LJFrontPanel> {
- public:
- static PassRefPtr<LJFrontPanel> create() { return adoptRef(new LJFrontPanel()); }
- bool writeLed(const String&);
- private:
- LJFrontPanel();
- };
- } // namespace WebCore
- #endif // LJFrontPanel_H
LJFrontPanel.cpp
点击(此处)折叠或打开
- #include "LJFrontPanel.h"
- namespace WebCore {
- LJFrontPanel::LJFrontPanel()
- {
- }
- bool LJFrontPanel::writeLed(const String& buff)
- {
- char tmpBuff[5] = {0};
- if((buff.isEmpty()) == true){
- return false;
- }
- else{
- printf("tmpBuff=%s\n",buff.utf8().data());
- strncpy(tmpBuff,buff.utf8().data(),5);
- return true;
- }
- }
- } // namespace WebCore
LJFrontPanel.idl
点击(此处)折叠或打开
- module window {
- interface LJFrontPanel{
- boolean writeLed(in DOMString buff);
- };
- }
修改WebCore/page/DOMWindow.h
点击(此处)折叠或打开
- //添加声明
- class LJFrontPanel;
- .
- .
- .
- //以下两句放在public里
- LJFrontPanel* ljfrontpanel() const;
- LJFrontPanel* optionalLJFrontPanel() const { return m_ljfrontpanel.get();}
- .
- .
- .
- //这句放在private里
- mutable RefPtr<LJFrontPanel> m_ljfrontpanel;
修改WebCore/page/DOMWindow.cpp
点击(此处)折叠或打开
- //引用头文件
- #include "LJFrontPanel.h"
-
- //创建js对象
- LJFrontPanel* DOMWindow::ljfrontpanel() const
- {
- if (!m_ljfrontpanel)
- m_ljfrontpanel = LJFrontPanel::create();
- return m_ljfrontpanel.get();
- }
-
- //消毁js对象,在DOMWindow::clear()方法中实现
- m_ljfrontpanel = 0;
修改WebCore/page/DOMWindow.idl
点击(此处)折叠或打开
- //添加
- attribute [Replaceable] LJFrontPanel ljfrontpanel;
测试
重编webkit,打开下面的测试页面
点击(此处)折叠或打开
- <html>
- <body>
- <script type="text/javascript">
- document.write("
============= This is from LJWebKit JSExt ljfrontpanel:"); - document.write(ljfrontpanel.writeLed("07:59"));
- </script>
- </body>
- </html>
备注
1、用上述方法创建的javascript对象,是作为DOMWindow的子对象,它是在window创建时创建,在window消毁前释放,即它的生命周和跟window是一样的
2、经测试,在javascript对象提供的方法中不能使用int型,而是使用long型,而js里的string型则对应于webkit里的String型。这点在给头端提供接口时要注意。
3、创建的对象作为DOMWindow的子对象,这个js实例只能由window创建,而用户是无法通过类似new LJFrontPanel()的方式创建的。
参考资料
1、
2、
3、
4、