目的
c++ 调用v8 引擎 , 使用javascript代码
code
以前写的,谁有用拿去好了
#ifdef NDEBUG
#undef NDEBUG
#endif
#define NODE_WANT_INTERNALS 1
#define _CRT_SECURE_NO_WARNINGS
#include <list>
#include <memory>
#include <string>
#include <vector>
#include "node.h"
#include "uv.h"
#include <assert.h>
#include <stdio.h>
#include "node_snapshot_builder.h"
#include "aliased_buffer.h"
#include "base_object-inl.h"
#include "env-inl.h"
#include "node_internals.h"
#include "util-inl.h"
#include "uv.h"
#include "v8.h"
#include "libplatform/libplatform.h"
#include <list>
#include <memory>
#include <string>
#include <vector>
/*namespace node {
const SnapshotData* SnapshotBuilder::GetEmbeddedSnapshotData() {
return nullptr;
}
}*/ // namespace node
//命令换成vcbuild release openssl-no-asm
//命令换成vcbuild release openssl-no-asm dll
#pragma comment(lib,"ws2_32.lib")
#pragma comment(lib,"winmm.lib")
#pragma comment (lib,"Advapi32.lib")
#pragma comment (lib,"iphlpapi.lib")
#pragma comment(lib, "psapi.lib")
#pragma comment(lib, "user32.lib")
#pragma comment(lib, "userenv.lib")
#pragma comment(lib, "Dbghelp.lib")
#pragma comment(lib, "Crypt32.lib")
#if 1
#pragma comment(lib, "base64.lib")
#pragma comment(lib, "base64_avx.lib")
#pragma comment(lib, "base64_avx2.lib")
#pragma comment(lib, "base64_sse41.lib")
#pragma comment(lib, "base64_sse42.lib")
#pragma comment(lib, "base64_ssse3.lib")
//
#pragma comment(lib, "cares.lib")
#pragma comment(lib, "ada.lib")
#pragma comment(lib, "brotli.lib")
#pragma comment(lib, "gtest.lib")
#pragma comment(lib, "gtest_main.lib")
//
//
#pragma comment(lib,"v8_init.lib")
#pragma comment(lib,"v8_libbase.lib")
#pragma comment(lib,"v8_libplatform.lib")
#pragma comment(lib,"v8_snapshot.lib")
#pragma comment(lib,"v8_base_without_compiler.lib")
#pragma comment(lib,"v8_compiler.lib")
#pragma comment(lib,"v8_turboshaft.lib")
#pragma comment(lib,"v8_zlib.lib")
#pragma comment(lib,"v8_initializers.lib")
//
//
//
#pragma comment(lib,"libuv.lib")
#pragma comment(lib,"llhttp.lib")
#pragma comment(lib,"uvwasi.lib")
#pragma comment(lib,"histogram.lib")
#pragma comment(lib,"simdutf.lib")
#pragma comment(lib,"nghttp2.lib")
#pragma comment(lib,"torque_base.lib")
//
#pragma comment(lib,"icui18n.lib")
#pragma comment(lib,"icudata.lib")
#pragma comment(lib,"openssl.lib")
#pragma comment(lib,"icutools.lib")
#pragma comment(lib,"icuucx.lib")
#pragma comment(lib,"zlib.lib")
#pragma comment(lib,"zlib_inflate_chunk_simd.lib")
#pragma comment(lib,"zlib_crc32_simd.lib")
#pragma comment(lib,"zlib_adler32_simd.lib")
#endif
//#pragma comment(lib, "node.lib")
#pragma comment(lib, "libnode.lib")
// Note: This file is being referred to from doc/api/embedding.md, and excerpts
// from it are included in the documentation. Try to keep these in sync.
// Snapshot support is not part of the embedder API docs yet due to its
// experimental nature, although it is of course documented in node.h.
using node::CommonEnvironmentSetup;
using node::Environment;
using node::MultiIsolatePlatform;
using v8::Context;
using v8::HandleScope;
using v8::Isolate;
using v8::Locker;
using v8::MaybeLocal;
using v8::V8;
using v8::Value;
#if 0
int main(int argc, char* argv[]) {
// Initialize V8.
v8::V8::InitializeICUDefaultLocation(argv[0]);
v8::V8::InitializeExternalStartupData(argv[0]);
std::unique_ptr<v8::Platform> platform = v8::platform::NewDefaultPlatform();
v8::V8::InitializePlatform(platform.get());
v8::V8::Initialize();
// Create a new Isolate and make it the current one.
v8::Isolate::CreateParams create_params;
create_params.array_buffer_allocator =
v8::ArrayBuffer::Allocator::NewDefaultAllocator();
v8::Isolate* isolate = v8::Isolate::New(create_params);
{
v8::Isolate::Scope isolate_scope(isolate);
// Create a stack-allocated handle scope.
v8::HandleScope handle_scope(isolate);
// Create a new context.
v8::Local<v8::Context> context = v8::Context::New(isolate);
// Enter the context for compiling and running the hello world script.
v8::Context::Scope context_scope(context);
{
// Create a string containing the JavaScript source code.
v8::Local<v8::String> source =
v8::String::NewFromUtf8Literal(isolate, "'Hello' + ', World!'");
// Compile the source code.
v8::Local<v8::Script> script =
v8::Script::Compile(context, source).ToLocalChecked();
// Run the script to get the result.
v8::Local<v8::Value> result = script->Run(context).ToLocalChecked();
// Convert the result to an UTF8 string and print it.
v8::String::Utf8Value utf8(isolate, result);
printf("%s\n", *utf8);
}
{
// Use the JavaScript API to generate a WebAssembly module.
//
// |bytes| contains the binary format for the following module:
//
// (func (export "add") (param i32 i32) (result i32)
// get_local 0
// get_local 1
// i32.add)
//
const char csource[] = R"(
let bytes = new Uint8Array([
0x00, 0x61, 0x73, 0x6d, 0x01, 0x00, 0x00, 0x00, 0x01, 0x07, 0x01,
0x60, 0x02, 0x7f, 0x7f, 0x01, 0x7f, 0x03, 0x02, 0x01, 0x00, 0x07,
0x07, 0x01, 0x03, 0x61, 0x64, 0x64, 0x00, 0x00, 0x0a, 0x09, 0x01,
0x07, 0x00, 0x20, 0x00, 0x20, 0x01, 0x6a, 0x0b
]);
let module = new WebAssembly.Module(bytes);
let instance = new WebAssembly.Instance(module);
instance.exports.add(3, 4);
)";
// Create a string containing the JavaScript source code.
v8::Local<v8::String> source =
v8::String::NewFromUtf8Literal(isolate, csource);
// Compile the source code.
v8::Local<v8::Script> script =
v8::Script::Compile(context, source).ToLocalChecked();
// Run the script to get the result.
v8::Local<v8::Value> result = script->Run(context).ToLocalChecked();
// Convert the result to a uint32 and print it.
uint32_t number = result->Uint32Value(context).ToChecked();
printf("3 + 4 = %u\n", number);
}
}
// Dispose the isolate and tear down V8.
isolate->Dispose();
v8::V8::Dispose();
v8::V8::DisposePlatform();
delete create_params.array_buffer_allocator;
return 0;
}
#endif
#if 1
static void Print(const v8::FunctionCallbackInfo<v8::Value>& info) {
v8::Isolate* isolate = info.GetIsolate();
v8::Local<v8::Context> context = isolate->GetCurrentContext();
std::string msg = *(v8::String::Utf8Value(isolate, info[0]->ToString(context).ToLocalChecked()));
std::cout << msg << std::endl;
}
// -------------------------end 1-----------------------------
int main(int argc, char* argv[]) {
// -------------------------begin 2-----------------------------
// Initialize V8.
//char SnapshotBlobCode[1024];
//v8::StartupData SnapshotBlob;
//SnapshotBlob.data = (const char*)SnapshotBlobCode;
//SnapshotBlob.raw_size = sizeof(SnapshotBlobCode);
//v8::V8::SetSnapshotDataBlob(&SnapshotBlob);
v8::V8::InitializeICUDefaultLocation(argv[0]);
v8::V8::InitializeExternalStartupData(argv[0]);
std::unique_ptr<v8::Platform> platform = v8::platform::NewDefaultPlatform();
v8::V8::InitializePlatform(platform.get());
v8::V8::Initialize();
// Create a new Isolate and make it the current one.
v8::Isolate::CreateParams create_params;
create_params.array_buffer_allocator =
v8::ArrayBuffer::Allocator::NewDefaultAllocator();
v8::Isolate* isolate = v8::Isolate::New(create_params);
// -------------------------end 2-----------------------------
{
// -------------------------begin 3-----------------------------
v8::Isolate::Scope isolate_scope(isolate);
// Create a stack-allocated handle scope.
v8::HandleScope handle_scope(isolate);
// Create a new context.
v8::Local<v8::Context> context = v8::Context::New(isolate);
// Enter the context for compiling and running the hello world script.
v8::Context::Scope context_scope(context);
// -------------------------end 3-----------------------------
// -------------------------begin 4-----------------------------
context->Global()->Set(context, v8::String::NewFromUtf8(isolate, "Print").ToLocalChecked(),
v8::FunctionTemplate::New(isolate, Print)->GetFunction(context).ToLocalChecked())
.Check();
// -------------------------end 4-----------------------------
{
// -------------------------begin 5-----------------------------
const char* csource = R"(
Print('hello world');
)";
// Create a string containing the JavaScript source code.
v8::Local<v8::String> source =
v8::String::NewFromUtf8(isolate, csource)
.ToLocalChecked();
// Compile the source code.
v8::Local<v8::Script> script =
v8::Script::Compile(context, source).ToLocalChecked();
// Run the script
auto _unused = script->Run(context);
}
// -------------------------end 5-----------------------------
}
// -------------------------begin 6-----------------------------
// Dispose the isolate and tear down V8.
isolate->Dispose();
v8::V8::Dispose();
V8::DisposePlatform();
//v8::V8::ShutdownPlatform();
delete create_params.array_buffer_allocator;
return 0;
// -------------------------end 6-----------------------------
}
namespace node {
const SnapshotData* SnapshotBuilder::GetEmbeddedSnapshotData() {
return nullptr;
}
} // namespace node
static int RunNodeInstance(MultiIsolatePlatform* platform,
const std::vector<std::string>& args,
const std::vector<std::string>& exec_args);
int main_(int argc, char** argv) {
argv = uv_setup_args(argc, argv);
std::vector<std::string> args(argv, argv + argc);
std::unique_ptr<node::InitializationResult> result =
node::InitializeOncePerProcess(
args,
{ node::ProcessInitializationFlags::kNoInitializeV8,
node::ProcessInitializationFlags::kNoInitializeNodeV8Platform });
for (const std::string& error : result->errors())
fprintf(stderr, "%s: %s\n", args[0].c_str(), error.c_str());
if (result->early_return() != 0) {
return result->exit_code();
}
std::unique_ptr<MultiIsolatePlatform> platform =
MultiIsolatePlatform::Create(4);
V8::InitializePlatform(platform.get());
V8::Initialize();
std::cout << "this is a test" << std::endl;
int ret = 0;
//int ret =
// RunNodeInstance(platform.get(), result->args(), result->exec_args());
V8::Dispose();
V8::DisposePlatform();
node::TearDownOncePerProcess();
return ret;
}
#if 0
int RunNodeInstance(MultiIsolatePlatform* platform,
const std::vector<std::string>& args,
const std::vector<std::string>& exec_args) {
int exit_code = 0;
node::EmbedderSnapshotData::Pointer snapshot;
auto snapshot_build_mode_it =
std::find(args.begin(), args.end(), "--embedder-snapshot-create");
auto snapshot_arg_it =
std::find(args.begin(), args.end(), "--embedder-snapshot-blob");
auto snapshot_as_file_it =
std::find(args.begin(), args.end(), "--embedder-snapshot-as-file");
if (snapshot_arg_it < args.end() - 1 &&
snapshot_build_mode_it == args.end()) {
const char* filename = (snapshot_arg_it + 1)->c_str();
FILE* fp = fopen(filename, "r");
assert(fp != nullptr);
if (snapshot_as_file_it != args.end()) {
snapshot = node::EmbedderSnapshotData::FromFile(fp);
}
else {
uv_fs_t req = uv_fs_t();
int statret = uv_fs_stat(nullptr, &req, filename, nullptr);
assert(statret == 0);
size_t filesize = req.statbuf.st_size;
uv_fs_req_cleanup(&req);
std::vector<char> vec(filesize);
size_t read = fread(vec.data(), filesize, 1, fp);
assert(read == 1);
snapshot = node::EmbedderSnapshotData::FromBlob(vec);
}
assert(snapshot);
int ret = fclose(fp);
assert(ret == 0);
}
std::vector<std::string> errors;
std::unique_ptr<CommonEnvironmentSetup> setup =
snapshot ? CommonEnvironmentSetup::CreateFromSnapshot(
platform, &errors, snapshot.get(), args, exec_args)
: snapshot_build_mode_it != args.end()
? CommonEnvironmentSetup::CreateForSnapshotting(
platform, &errors, args, exec_args)
: CommonEnvironmentSetup::Create(platform, &errors, args, exec_args);
if (!setup) {
for (const std::string& err : errors)
fprintf(stderr, "%s: %s\n", args[0].c_str(), err.c_str());
return 1;
}
Isolate* isolate = setup->isolate();
Environment* env = setup->env();
{
Locker locker(isolate);
Isolate::Scope isolate_scope(isolate);
HandleScope handle_scope(isolate);
Context::Scope context_scope(setup->context());
MaybeLocal<Value> loadenv_ret;
if (snapshot) {
loadenv_ret = node::LoadEnvironment(env, node::StartExecutionCallback{});
}
else {
loadenv_ret = node::LoadEnvironment(
env,
// Snapshots do not support userland require()s (yet)
"if (!require('v8').startupSnapshot.isBuildingSnapshot()) {"
" const publicRequire ="
" require('module').createRequire(process.cwd() + '/');"
" globalThis.require = publicRequire;"
"} else globalThis.require = require;"
"globalThis.embedVars = { nön_ascıı: '🏳️🌈' };"
"require('vm').runInThisContext(process.argv[1]);");
}
if (loadenv_ret.IsEmpty()) // There has been a JS exception.
return 1;
exit_code = node::SpinEventLoop(env).FromMaybe(1);
}
if (snapshot_arg_it < args.end() - 1 &&
snapshot_build_mode_it != args.end()) {
snapshot = setup->CreateSnapshot();
assert(snapshot);
FILE* fp = fopen((snapshot_arg_it + 1)->c_str(), "w");
assert(fp != nullptr);
if (snapshot_as_file_it != args.end()) {
snapshot->ToFile(fp);
}
else {
const std::vector<char> vec = snapshot->ToBlob();
size_t written = fwrite(vec.data(), vec.size(), 1, fp);
assert(written == 1);
}
int ret = fclose(fp);
assert(ret == 0);
}
node::Stop(env);
return exit_code;
}
#endif
#endif