
VFP里面运行JS,可以利用JS很多很多资源,做到以前不能做到的事情,那今天更高级的混合方式来了,混合quickjs来做一些很酷的工作。
首先来看quickjs引擎能做的工作,将JS文件编译成EXE
1 如下JS文件Hello.js
console.log("Hello World");2 点开始菜单运行CMD,进行DOS环境,执行如下指令,生成hello.js文件
qjsc -e -o hello.c hello.js
生成的hello.c文件
/* File generated automatically by the QuickJS compiler. */
#include "quickjs-libc.h"
const uint32_t qjsc_hello_size = 78;
const uint8_t qjsc_hello[78] = {
0x02, 0x04, 0x0e, 0x63, 0x6f, 0x6e, 0x73, 0x6f,
0x6c, 0x65, 0x06, 0x6c, 0x6f, 0x67, 0x16, 0x48,
0x65, 0x6c, 0x6c, 0x6f, 0x20, 0x57, 0x6f, 0x72,
0x6c, 0x64, 0x10, 0x68, 0x65, 0x6c, 0x6c, 0x6f,
0x2e, 0x6a, 0x73, 0x0e, 0x00, 0x06, 0x00, 0xa0,
0x01, 0x00, 0x01, 0x00, 0x03, 0x00, 0x00, 0x14,
0x01, 0xa2, 0x01, 0x00, 0x00, 0x00, 0x38, 0xe1,
0x00, 0x00, 0x00, 0x42, 0xe2, 0x00, 0x00, 0x00,
0x04, 0xe3, 0x00, 0x00, 0x00, 0x24, 0x01, 0x00,
0xcd, 0x28, 0xc8, 0x03, 0x01, 0x00,
};
static JSContext *JS_NewCustomContext(JSRuntime *rt)
{
JSContext *ctx = JS_NewContextRaw(rt);
if (!ctx)
return NULL;
JS_AddIntrinsicBaseObjects(ctx);
JS_AddIntrinsicDate(ctx);
JS_AddIntrinsicEval(ctx);
JS_AddIntrinsicStringNormalize(ctx);
JS_AddIntrinsicRegExp(ctx);
JS_AddIntrinsicJSON(ctx);
JS_AddIntrinsicProxy(ctx);
JS_AddIntrinsicMapSet(ctx);
JS_AddIntrinsicTypedArrays(ctx);
JS_AddIntrinsicPromise(ctx);
JS_AddIntrinsicBigInt(ctx);
return ctx;
}
int main(int argc, char **argv)
{
JSRuntime *rt;
JSContext *ctx;
rt = JS_NewRuntime();
js_std_set_worker_new_context_func(JS_NewCustomContext);
js_std_init_handlers(rt);
JS_SetModuleLoaderFunc(rt, NULL, js_module_loader, NULL);
ctx = JS_NewCustomContext(rt);
js_std_add_helpers(ctx, argc, argv);
js_std_eval_binary(ctx, qjsc_hello, qjsc_hello_size, 0);
js_std_loop(ctx);
JS_FreeContext(ctx);
JS_FreeRuntime(rt);
return 0;
}
3 用gcc 来生成exe程序
gcc hello.c libquickjs.dll -I..\ -o hello.exe
可以看到hello.exe生成成功,并且运行了。
这里利用了 gcc 来生成exe ,那么生成dll 可以吗?
答案是肯定的。
我们再试着用gcc 来生成dll 让VFP调用看看?
1 头文件 dll.h,可以用记事本来生成。
#ifdef BUILD_DLL /* DLL export */
#define EXPORT __declspec(dllexport)
#else /* EXE import */
#define EXPORT __declspec(dllimport)
#endif
EXPORT int hello(void);2 dll.c文件
#include "dll.h"
EXPORT int hello(void)
{
return 123;
}
3 开始编译生成
编译dll.c
gcc -c -DBUILD_DLL dll.c意要使用要使用-DBUILD_DLL来设置宏BUILD_DLL
创建dll
gcc -shared -o dll.dll dll.o -Wl,--out-implib,libmessage.a这一步要详细说明一下
-shared参数用来创建共享库,在windows中为dll -Wl 等待下一条信息进行连接 --out-implib是给连接程序ld使用的,用于创建要连接dll需要的import library
这样就会生成dll.dll
VFP 调用代码如下
DECLARE INTEGER hello IN dll.dll
?hello()
CLEAR DLLS
恩,运行完美。
待完成的开发和测试
拥抱JS,VFP可以拥有更多的未来。比如Web3,AI,机器学习等等。
这本犀牛书可以入手。不到50块,少抽几包烟你就可以学会一项新的功能,让你可以飞得更高。