CEF框架:c++和JS交互走過的坑


網上有許多教你如何進行使用JS調用C++的教程,但是大多數都是交代的不是十分清晰,這里主要講我遇到的坑。主要以cefsimple來講。

我的目錄大致為:

cef1.png

1如何開啟一個多線程

只有CEF框架中開啟一個子線程,才能完成C++和JavaScript之間的交互,而開啟線程只需要調用一下這個函數——CefExecuteProcess即可生成一個子線程。但是這個函數什么時候調用,和在哪里調用,和怎么調用,網上說的一點也不清晰。

在cefsimple中cefsimple_win.cc中就存在了着這個方法,所以我們只需要修改一下這個方法即可

//大概在48行左右
  // CEF applications have multiple sub-processes (render, plugin, GPU, etc)
  // that share the same executable. This function checks the command-line and,
  // if this is a sub-process, executes the appropriate logic.
  //上面的那句話的大概意思是,主要CEF框架有許多子進程,這個方法主要是檢測是否有子進程,如果有子進程,就執行子進程
  int exit_code = CefExecuteProcess(main_args, nullptr, sandbox_info);

這個方法——CefExecuteProcess,可以先不看,

CEF_GLOBAL int CefExecuteProcess(const CefMainArgs& args,
                                 CefRefPtr<CefApp> application,
                                 void* windows_sandbox_info) {
  const char* api_hash = cef_api_hash(0);
  if (strcmp(api_hash, CEF_API_HASH_PLATFORM)) {
    // The libcef API hash does not match the current header API hash.
    //當前API的hash值和當前進程的頭APIhash不匹配,退出開啟進程。
    NOTREACHED();
    return 0;
  }

  // AUTO-GENERATED CONTENT - DELETE THIS COMMENT BEFORE MODIFYING

  // Unverified params: application, windows_sandbox_info(一個檢測信息)


  // Execute
  int _retval = cef_execute_process(&args, CefAppCppToC::Wrap(application),
                                    windows_sandbox_info);

  // Return type: simple
  return _retval;
}

重要的是這個方法的第二個參數是一個CefApp,也就是我們所要執行子進程對象,所以我們可以先不管它,直接創建子進程對象放上先。大概操作為如下:

CefRefPtr<csubclassHandler> appa(new csubclassHandler);//csubclassHandler這個是我實現了CefApp的類
int exit_code = CefExecuteProcess(main_args, appa.get() , nullptr);

這就完成了開啟線程的操作,是不是很簡單,哈哈哈哈

重寫GetRenderProcessHandler()這個方法

//subhandler.h_>

#include "include/cef_app.h"

class csubclassHandler :
public CefApp,
public CefRenderProcessHandler
{

public:
    csubclassHandler();
    ~csubclassHandler();

    /****/
   //這個方法一定要重寫,不然的話browser對象不能收到JS發來的請求
    virtual CefRefPtr<CefRenderProcessHandler> GetRenderProcessHandler() OVERRIDE {
    return this;
  } 
    /***/
    

    void OnContextCreated(CefRefPtr<CefBrowser> browser, CefRefPtr<CefFrame> frame, CefRefPtr<CefV8Context> context) OVERRIDE;
  private:
	  IMPLEMENT_REFCOUNTING(csubclassHandler);
};

剩下的操作跟着官方文檔和博客都能完成相應的操作。

這是我的小demo:

git@github.com:whllow/C-.git


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM