Duktape Example

Author: Dave
Date: 06.07.15 - 6:53am

Here is an small but interesting program that utilizes the duktape javascript engine.

In the last post I was wondering how to handle a COM method which returned a live object instance, and how to have the methods on that sub object returned to the js environment and route calls from that specific instance back to that specific object.

The below template demonstrates how to accomplish this.

javascript executed:
function testClass(){
	this.ReadAll = function(){
		print('testClass.ReadAll() called'); 	

var ts = nativeFunc('file.txt');
print('ts=' + ts);
print('ts.hInst = ' + ts.hInst);
print('test complete');

C program:
//ref: http://stackoverflow.com/questions/30296953/export-c-class-to-duktape

#include "./duk/duktape.h"
#include <conio.h>

	nativefunc(file.txt) returning a new testClass instance
	ts=[object Object]
	ts.hInst = 12345
	testClass.ReadAll() called
	textstream instance 12345 released!
	test complete

duk_ret_t js_testClass_dtor(duk_context *ctx)
	int hInst = 0;

    // The object to delete is passed as first argument
	//retrieve this.hInst numeric value
    duk_get_prop_string(ctx, 0, "hInst");
	hInst = duk_to_number(ctx, -1); 

	printf("textstream instance %d released!\n", hInst);
    return 0;


int nativeFunc(duk_context *ctx) {
	int i;
	const char* arg0 = 0;
	//int n = duk_get_top(ctx);  //arg count

	arg0 = duk_safe_to_string(ctx, 0);

	printf("nativefunc(%s) returning a new testClass instance\n", arg0);

	//create a new testClass javascript object instance
	duk_get_global_string(ctx, "testClass"); 
	duk_new(ctx, 0); 

	//set this.hInst = 12345
	duk_push_number(ctx, 12345); 
	duk_put_prop_string(ctx, -2, "hInst"); 

	//register a C function to run when js obj released
	duk_push_c_function(ctx, js_testClass_dtor, 1);
	duk_set_finalizer(ctx, -2);	 

	return 1;

int main(int argc, char *argv[]) {

	duk_context *ctx = duk_create_heap_default();

	char* mClass = "function testClass(){\n"
				"   this.hInst=0;\n"
				"	this.ReadAll = function(){\n"
				"		print('testClass.ReadAll() called');\n" 	
				"	}\n"

	//add this script fragment to the current context (used latter)
	//safe to call eval to avoid fatal panic handler on syntax error
	duk_push_string(ctx, mClass);
	if (duk_peval(ctx) != 0) {
		printf("eval failed: %s\n", duk_safe_to_string(ctx, -1));
		goto finished;
	//register a new native function for use in JS
	duk_push_c_function(ctx, nativeFunc, DUK_VARARGS);
	duk_put_prop_string(ctx, -2, "nativeFunc");
	char* test = "var ts = nativeFunc('file.txt');\n"
			"print('ts=' + ts);\n"
			"print('ts.hInst = ' + ts.hInst);\n"
			"print('test complete');";

	//now we will run a block of JS in configured envirnoment..
	duk_push_string(ctx, test);
	if (duk_peval(ctx) != 0) {
		printf("eval failed: %s\n", duk_safe_to_string(ctx, -1));


	return 0;

Comments: (0)

Leave Comment:
Email: (not shown)
Message: (Required)
Math Question: 64 + 36 = ? followed by the letter: E 

About Me
More Blogs
Main Site
Console tricks
FireFox temp dir
OCX License
Extract substring
VB6 Console Apps
VB6 Debugger View As Hex tooltips
VB6 - C Share registry data
VB6 Addin Missing Menus
VB6 Class Init Params
VB6 isIn function
Python and VB6
Python pros and cons
download web Dir
vc rand in python
VB6 Language Enhancement
Register .NET as COM
UDT Tricks pt2
Remote Data Extraction
Collection Extender
VB6 FindResource
DirList Single Click
Reset CheckPoint VPN Policy
VB6 BSTR Oddities Explained
SafeArrays in C
BSTR and Variant in C++
Property let optional args
Misc Libs
Enum Named Pipes
Vb6 Collection in C++
VB6 Overloaded Methods
VB6 Syncronous Socket
Simple IPC
VB6 Auto Resize Form Elements
Mach3 Automation
Exit For in While
C# self register ocx
VB6 Class Method Pointers
JS Debugger
Duktape Debug Protocol
QtScript 4 VB
Vb6 Named Args
vb6 Addin Part 2
VB6 Addin vrs Toolbars
OpenFile Dialog MultiSelect
Duktape Example
DukTape JS
VB6 Unsigned
.Net version
TitleBar Height
.NET again
VB6 Self Register OCXs
Query Last 12 Mos
Progid from Interface ID
VB6 to C Array Examples
Human Readable Variant Type
ScriptBasic COM Integration
CodeView Addin
ScriptBasic - Part 2
Script Env
printf override
History Combo
Disable IE
API Hooking in VB6
Addin Hook Events
FastBuild Addin
VB6 MemoryWindow
Link C Obj Files into VB6
Vb6 Standard Dlls
CStr for Pascal
Lazarus Review
asprintf for VS
VB6 GlobalMultiUse
Scintilla in VB6
Dynamic Highlight
WinVerifyTrust, CryptMsgGetParam VB6
MS GLEE Graphing
printf for VB6
C# App Config
Tero DES C# Test
VC 2008 Bit Fields
Speed trap
C# Db Class Generator
VB6 vrs .NET (again)
FireFox Whois Extension
git and vb6
Code Additions
Compiled date to string
C# ListView Sorter
VB6 Wish List
C# Process Injection
C# PE Offset Calculator
VB6 Async Download
Show Desktop
coding philosophy
Code release
Dll Not Found in IDE
Advanced MSScript Control
random tip
Clipart / Vector Art
VB6 Callback from C#
Binary data from VB6 to C#
CSharp and MsScriptControl
HexDumper functions
Js Beautify From VB6 or C#
vb6 FormPos
Inline Asm w VB6
The .NET Fiasco
One rub on computers
Universal extractor