Sign in to follow this  
Followers 0
1RV34

Calls to "_class::property" stuff

9 posts in this topic

#1 ·  Posted (edited)

Well I asked it before in an other topic but no one replies there so I thought I'll start it as a seperate topic.

Ok I'm kinda stuck & hope somebody can help me with this here.

I'm following this tutorial but I can't get stuff to work.

I have a dll & it has like COM Properties or idk like "_class::propperty" but how do I call them?

using DLLCall (like I tried) or do I need the ObjGet function? Or both of them combined?

I haven't used dll's & com stuff before but now I need to and now this tutorial did help me understand DLLCall better.

Anybody can push me in the right direction? Do I need DLLCall or ObjGet or both? And how do I use those things from the dll (those that look like "_class::property") in AutoIt?

Edit: I also found a function called "DllGetClassObject" in the dll, can I use that to create an object and then use that to call the properties? If so how?

When I tried it myself it crashed with exit code -1073741819.

Edit: I now noticed some of them are methods and others properties, can I both use methods and get properties?

Edited by 1RV34

MsgBox(0x40040, "", "Hello Forum!")

Share this post


Link to post
Share on other sites



Some aditional information:

Using a DLL viewer I saw these functions:

  • DllCanUnloadNow
  • DllGetClassObject
  • DllRegisterServer
  • DllUnregisterServer
Which indicate I can register the DLL using
regsvr32 "C:pathtothedll.dll"
and I think I should then be able to use ObjCreate("obj.type") to continue.

But how do I find that "obj.type" and then call to "_clsClass::mtdMethod" & "_clsClass::prpProperty"?

I'm really stuck and any hint or push in the right direction would help a lot :/


MsgBox(0x40040, "", "Hello Forum!")

Share this post


Link to post
Share on other sites

hi 1RV34,

ObjCreate is fine for COM objects.

Unfortunately you gave us very little (relevant, specific) information ;) so that's about all the help I can offer at the moment.

What is the name of the dll? Where can one find it? and its documentation?

Also, please post the code you tried, and any errors you might have encountered.

Help us help you :)

-smartee

Share this post


Link to post
Share on other sites

#4 ·  Posted (edited)

If the COM dll was compiled with type information you should be able to load it into a Type Library Viewer to see the supported interfaces. Basically if the library is really an ActiveX Control or has Automation support, you can load from a scripting language. Otherwise if it's virtual method table only, you need to access it from a compiled language. If it supports Automation chances are it has a Type Library. So try a Type Library viewer. I'm sure you can download a free one someplace.

It's been quite a few years since I did COM programming. So this is just from vague memory. Hope I pointed you in the right direction.

Edited by MilesAhead

Share this post


Link to post
Share on other sites

What is the name of the dll? Where can one find it? and its documentation?

The name is "SnelStartGateWay.dll". It is ment to make communication between your program and SnelStart possible.

It can be found in "C:Program Files (x86)SnelStartV1000" (V1000 is version dependable but my script finds the right path). It comes with the program.

The documentation is in Dutch so I don't know if that will help you much, but what I can do is give the (vb6) example in it if that might help.

Private Sub mtdToevoegenJournaalPost()
  On Error GoTo ErrorHandler
  'Declaratie variabelen
  Dim mvrGWaySnelStart As clsGWaySnelStart
  Dim mvrAdmiInEuro As Boolean
  Dim mvrGbOmschrijving As String
  'Aanmaken nieuwe ToegangsObject
  Set mvrGWaySnelStart = New clsGWaySnelStart
  With mvrGWaySnelStart
    'Openen administratie
    .mtdGWayAdmiOpenen "C:SnelStartAdministraties", "SnelStart Voorbeeldbedrijf"
    'Uitlezen of Administratie in Euro's is
    mvrAdmiInEuro = .prpGWayAdmiInEuroGet
    Debug.Print "Adminitratie in Euro is " & mvrAdmiInEuro
    'Uitlezen omschrijving van Grootboek 9990
    mvrGbOmschrijving = .mtdGWayGrootboekOmschrijving(9990)
    Debug.Print "Omschrijving van GrootBoek 9990 is " & mvrGbOmschrijving
    'Journaalpost openen
    .mtdGWayJpAanmaken Now, 9990, "ABC", "OmschrijvingXYZ"
    'Regels aan JournaalPost toevoegen
    .mtdGWayJpRegelToevoegenV616 8001, "DebetZZZZ", 100, 0
    .mtdGWayJpRegelToevoegenV616 8002, "CreditYYYY", 0, 75
    .mtdGWayJpRegelToevoegenV616 8002, "CreditYYYY", 0, 25
    'Journaalpost sluiten
    .mtdGWayJpSluiten
    'Sluiten administratie
    .mtdGWayAdmiSluiten
    'Starten applicatie
    .mtdGWayRunSnelStart "C:SnelStartAdministratiesSnelStart Voorbeeldbedrijf"
  End With
  Exit Sub
ErrorHandler:
  mtdMsg mtdGWayFoutBoodschap("mtdToevoegenJournaalPost"), vbInformation
End Sub

Private Sub mtdWijzigenJournaalPost()
  On Error GoTo ErrorHandler
  'Declaratie variabelen
  Dim mvrGWaySnelStart As clsGWaySnelStart
  Dim mvrGWayJournaalPost As clsGWayJournaalPost
  Dim mvrGWayJournaalRegel As clsGWayJournaalRegel
  'Aanmaken nieuwe ToegangsObject
  Set mvrGWaySnelStart = New clsGWaySnelStart
  With mvrGWaySnelStart
    'Openen administratie
    .mtdGWayAdmiOpenen "C:SnelStartAdministraties", "SnelStart Voorbeeldbedrijf"

    '-----------------------------------------------------
    'Voorbeeld 1 met verwijderen van een journaalpostregel
    '-----------------------------------------------------
    Set mvrGWayJournaalPost = .mtdGWayJournaalPostGet(502)
    'Wijzig het GrootboekNummer op vierde journaalpostregel
    mvrGWayJournaalPost.mtdGetJournaalRegelOpIndex(4).prpGWayGrootboekNummerSet = 3006
    'Voeg 4e en 5e journaalpostregel samen
    mvrGWayJournaalPost.mtdGetJournaalRegelOpIndex(4).prpGWayDebetSet = mvrGWayJournaalPost.mtdGetJournaalRegelOpIndex(4).prpGWayDebetGet + _
                                                                        mvrGWayJournaalPost.mtdGetJournaalRegelOpIndex(5).prpGWayDebetGet
    mvrGWayJournaalPost.mtdGetJournaalRegelOpIndex(4).prpGWayCreditSet = mvrGWayJournaalPost.mtdGetJournaalRegelOpIndex(4).prpGWayCreditGet + _
                                                                         mvrGWayJournaalPost.mtdGetJournaalRegelOpIndex(5).prpGWayCreditGet
    'Verwijder de 5e journaalpostregel
    mvrGWayJournaalPost.mtdJpRegelRemove 5
    'Voer wijziging door
    .mtdGWayJpWijzigen mvrGWayJournaalPost

    '---------------------------------------------------
    'Voorbeeld 2 met toevoegen van een journaalpostregel
    '---------------------------------------------------
    Set mvrGWayJournaalPost = .mtdGWayJournaalPostGet(503)
    'Wijzig totaalbedrag
    mvrGWayJournaalPost.mtdGetJournaalRegelOpIndex(1).prpGWayDebetSet = mvrGWayJournaalPost.mtdGetJournaalRegelOpIndex(1).prpGWayDebetGet + 100
    'Voeg extra regel toe
    Set mvrGWayJournaalRegel = mvrGWayJournaalPost.mtdJpRegelAdd
    'Vul de nieuwe regel
    mvrGWayJournaalRegel.prpGWayDebetSet = 0
    mvrGWayJournaalRegel.prpGWayCreditSet = 100
    mvrGWayJournaalRegel.prpGWayBtwIDSet = encGWayBtwIDGeen
    mvrGWayJournaalRegel.prpGWayBtwPercentageSet = 0
    mvrGWayJournaalRegel.prpGWayBtwTypeSet = encGWayBtwTypeNvt
    mvrGWayJournaalRegel.prpGWayFactuurNummerSet = "20050918"
    mvrGWayJournaalRegel.prpGWayFactuurRelatiecodeSet = 2
    mvrGWayJournaalRegel.prpGWayGrootboekNummerSet = 8095
    mvrGWayJournaalRegel.prpGWayOmschrijvingSet = "extra regel"
    'Voer wijziging door
    .mtdGWayJpWijzigen mvrGWayJournaalPost

    'Sluiten administratie
    .mtdGWayAdmiSluiten
    'Starten applicatie
    .mtdGWayRunSnelStart "C:SnelStartAdministratiesSnelStart Voorbeeldbedrijf"
  End With
  Exit Sub
ErrorHandler:
  mtdMsg mtdGWayFoutBoodschap("mtdWijzigenJournaalPost"), vbInformation
End Sub

Private Sub mtdInkoopOrderToevoegen()
  On Error GoTo ErrorHandler
  'Declaratie variabelen
  Dim mvrGWaySnelStart As clsGWaySnelStart
  Dim mvrGWayJournaalPost As clsGWayJournaalPost
  Dim mvrGWayJournaalRegel As clsGWayJournaalRegel
  'Aanmaken nieuwe ToegangsObject
  Set mvrGWaySnelStart = New clsGWaySnelStart
  With mvrGWaySnelStart
    'Openen administratie
    .mtdGWayAdmiOpenen "C:SnelStartAdministraties", "SnelStart Voorbeeldbedrijf"

    'Inkooporder aanmaken
    .mtdGWayInkoopOrderAanmaken 1, 30123, Now, "Inkoop via gateway", "memo-tekst", "bk inkoop"
    'Regels toevoegen
    .mtdGWayInkoopOrderRegelToevoegenArtikelMetDefaults 12, 100
    .mtdGWayInkoopOrderRegelToevoegenArtikel 12, "Eigen omschrijving", 50, 1.12, 10, 1
    .mtdGWayInkoopOrderRegelToevoegenTekst "Echte tekstregel", 0, 0
    .mtdGWayInkoopOrderRegelToevoegenTekst "Tekstregel met bedrag en kostenplaats", 10, 2
    'Voer wijziging door
    .mtdGWayInkoopOrderSluiten

    'Sluiten administratie
    .mtdGWayAdmiSluiten
    'Starten applicatie
    .mtdGWayRunSnelStart "C:SnelStartAdministratiesSnelStart Voorbeeldbedrijf"
  End With
  Exit Sub
ErrorHandler:
  mtdMsg mtdGWayFoutBoodschap("mtdWijzigenJournaalPost"), vbInformation
End Sub

Private Sub mtdVerkoopAbonnementOrderToevoegen()
  On Error GoTo ErrorHandler
  'Declaratie variabelen
  Dim mvrGWaySnelStart As clsGWaySnelStart

  Dim mvrSjabloonID As Long
  Dim mvrRelatieCode As Long
  Dim mvrDatum As Date
  Dim mvrOmschrijving As String
  Dim mvrOrderMemo As String
  Dim mvrKostenplaatsenNummer As Long
  Dim mvrBetalingsKenmerk As String
  Dim mvrVerkoperLoginNaam As String

  Dim mvrAbonnementIntervalSoort As enmGWayAbonnementInterval
  Dim mvrAbonnementIntervalAantal As Variant
  Dim mvrAbonnementTijdstipMaand As Variant
  Dim mvrAbonnementTijdstipWeekDag As Variant
  Dim mvrAbonnementTijdstipMaandDag As Variant
  Dim mvrAbonnementTijdstipWeekVanMaandDag As Variant
  Dim mvrAbonnementBegindatum As Variant
  Dim mvrAbonnementEindDatum As Variant
  Dim mvrAbonnementEindeNaAantal As Variant

  'Aanmaken nieuwe ToegangsObject
  Set mvrGWaySnelStart = New clsGWaySnelStart
  With mvrGWaySnelStart
    'Openen administratie
    .mtdGWayAdmiOpenen "C:SnelStartAdministraties", "SnelStart Voorbeeldbedrijf"

    'Verkooporder aanmaken
    mvrSjabloonID = 1
    mvrRelatieCode = 10001
    mvrDatum = Now
    mvrOrderMemo = "memo"
    mvrKostenplaatsenNummer = 0
    mvrBetalingsKenmerk = "BK"

Also, please post the code you tried, and any errors you might have encountered.

I have tried some codes, none worked (they are probably very noobish because I have never used them before).

Codes i tried:

$dll = DllOpen($dllPath)

If $dll = -1 Then
    _Err("Kon SnelStartGateWay.dll niet openen!")
EndIf

$result = DllCall($dll, "none", "_clsGWaySnelStart::mtdGWayAdmiOpenen"); also tried "DllGetClassObject" as function, this made AutoIt time-out/crash after a while
$error = @error

If $error Then
    _Err("DLLCall #1 Error: " & $error)
EndIf

_Msg("DLLCall #1 Result: " & $result)
DllClose($dll)

$obj = ObjCreate("SnelStartGateWay.application")
$error = @error

If $error Then
    _Msg("SnelStart Sync maakt een poging om SnelStartGateWay.dll te registreren." & @LF & "Druk op OK.")
    Break(0)
    RunWait('regsvr32 "' & $dllPath & '"')
    $obj = ObjCreate("SnelStartGateWay.application")
    $error = @error

    If $error Then
        Run('regsvr32 /u "' & $dllPath & '"')
    EndIf

    Break(1)

    If $error Then
        _Err("ObjCreate #1 Error: " & $error)
    EndIf
EndIf

$dll = _WinAPI_LoadLibrary($dllPath)

If $dll Then
    ; ... (didn't know what i would have to do here :P)
_WinAPI_FreeLibrary($dll)
Else
    _Err("Kon SnelStartGateWay.dll niet openen!"); it did not give this error message tho XD
EndIf

MsgBox(0x40040, "", "Hello Forum!")

Share this post


Link to post
Share on other sites

#6 ·  Posted (edited)

Does the VB6 code work? If not then the dll is likely not registered on the system. Search the registry for the string you use in ObjCreate() function. If that string is not found then it's not registered. Try regsvr32 or one of those shell extensions that registers and unregisters COM libraries.

edit: also if it's a licensed ActiveX Control designed to drop on a form such as in VB6, it won't work without the .lic file. It would need a design time license before it would instantiate on the form(the .lic file.) A program using it will run but you can't use it in a form designer without the license if it's a licensed control.

First thing I'd do is try to get the VB6 example to go. If it doesn't you're likely wasting your time.

Edited by MilesAhead

Share this post


Link to post
Share on other sites

#7 ·  Posted (edited)

Hi 1RV34,

Now that's a greatly informative post! :)

I don't understand a word of dutch however ;) , but with Google Translate I managed to cobble up a couple lines to get you started,

$oMyError = ObjEvent("AutoIt.Error", "MyErrFunc") ; Install a custom error handler

$oSnel = ObjCreate("SnelStartGateWay.clsGWaySnelStart")
If IsObj($oSnel) Then
    MsgBox(64, "", "Object created successfully")
EndIf

MsgBox(64, "Version", $oSnel.prpGWayVersieGateWayGet())

$oSnel2 = ObjCreate("SnelStartGateWay.clsGWArtikel")
If IsObj($oSnel2) Then
    MsgBox(64, "", "Object created successfully")
EndIf

; This is the custom error handler
Func MyErrFunc()
    $HexNumber = Hex($oMyError.number, 8)
    MsgBox(0, "", "We intercepted a COM Error !" & @CRLF & _
            "Number is: " & $HexNumber & @CRLF & _
            "Windescription is: " & $oMyError.windescription & @CRLF & _
            "Source is: " & $oMyError.source & @CRLF & _
            "Description is: " & $oMyError.description & @CRLF & _
            "Helpfile is: " & $oMyError.helpfile & @CRLF & _
            "Helpcontext is: " & $oMyError.helpcontext & @CRLF & _
            "Lastdllerror is: " & $oMyError.lastdllerror & @CRLF & _
            "Scriptline is: " & $oMyError.scriptline)
EndFunc   ;==>MyErrFunc

Hope this little tidbit helps ;)

-smartee

Edit: some spelling, greets

Edited by smartee

Share this post


Link to post
Share on other sites

Yes

$oSnel = ObjCreate("SnelStartGateWay.clsGWaySnelStart")

Just that line helped a lot already!

I didn't know which function I needed (DllCall, ObjCreate or _WinAPI_LoadLibrary) and also if I needed ObjCreate I didn't know I needed "SnelStartGateWay.clsGWaySnelStart" I tried stuff like "SnelStartGateWay.application" XD (never used it before o.o)

Thanks for this example & making me understand ObjCreate more! :oops:


MsgBox(0x40040, "", "Hello Forum!")

Share this post


Link to post
Share on other sites

The name of the automation used for IDispatch is always in the registry somewhere as a clsid. For instance if you have Scripting Dictionary installed you'll see "Scripting.Dictionary" defined somewhere. Usually things that support IDispatch have type library information. Languages like C++ often you can import the type library and the Intellisense will automatically pick up the methods once you create an instance. A lot of program code is in English when the language of origin is not just because so many compilers etc.. were created in English.

Share this post


Link to post
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!


Register a new account

Sign in

Already have an account? Sign in here.


Sign In Now
Sign in to follow this  
Followers 0

  • Similar Content

    • Luigi
      By Luigi
      Greetings, someone can give a exemple, how send a error from a C#'s dll to AutoIt?
      I use this line, to send an error... but, I want get a error code In AutoIt with macro @error, it's possible?
       
      throw new ArgumentException("arquivo map não existe", "value" ); In this way, work, I know ther are error, but, @errror always is zero.
      I don't want this, I want a number as error code.
      Can you help me?
       
      Best regards
    • nss
      By nss
      Hi all,
       
      I am making a program in which I use Bass audio library (with the wrapper for autoit that I found here on forums I think) because of its support for dx effects.
      My problem, though, is that when effects as reverb or echo/delay are added, the channel length is not extended as to fit the tail of the effect, so if the file was really short, you wouldn't even hear the reverb at all.
      I've tried setting the  buffer parameter even to 60k ms, updating the channel length to 60k ms, but nothing makes it so that the effects aren't being cut off.
      I've heard that I could add silence manually to wave files by adding the chr(0) characters, but haven't had any luck doing that, either.
      What I'm doing:
      initialize bass use streamCreateFile to load the wave file with the fx flag and length parameter set to 60000 set the config buffer to 60000 use channel set fx to add dx8 reverb use channel play to play the sound use bass update to update the length to 60000  
      I even tried having only silence in one wave file and tried joining two wave files together, but that didn't work either.
       
      Any help would be very much appreciated.
    • luckyluke
      By luckyluke
      Hello,
      Im trying to read the output from CMD using Dllcall, here is my code:
      #include <WinAPI.au3> #include <array.au3> Global Const $STD_OUTPUT_HANDLE = -11 Global Const $_CONSOLE_SCREEN_BUFFER_INFO = _ "struct;int dwSizeX;" & _ "short dwSizeY;" & _ "short dwCursorPositionX;" & _ "short dwCursorPositionY;" & _ "short wAttributes;" & _ "short Left;" & _ "short Top;" & _ "short Right;" & _ "short Bottom;" & _ "short dwMaximumWindowSizeX;" & _ "short dwMaximumWindowSizeY;endstruct" $pCmd = Run( "cmd.exe" ) Sleep(1000) $hCmd = WinGetHandle("") ConsoleWrite('handle:' & $hCmd & @CRLF) $aRet = DllCall("kernel32.dll", "int", "AttachConsole", "dword", $pCmd) ;_ArrayDisplay($aRet) If $aRet[0] <> 0 Then $vHandle_data='' $vHandle='' $vHandle_data = DllStructCreate($_CONSOLE_SCREEN_BUFFER_INFO) ; Screen Buffer structure $aRet1 = DllCall("kernel32.dll", "hwnd", "GetStdHandle", "dword", $STD_OUTPUT_HANDLE) if not @error Then $vHandle = $aRet1[0] $aRet = DllCall("kernel32.dll", "int", "GetConsoleScreenBufferInfo", "hwnd", $vHandle, _ "ptr", $vHandle_data) MsgBox(0, '1',DllStructGetData($vHandle_data, 'dwSizeX') & _WinAPI_GetLastErrorMessage()) EndIf It did not work, i got the message 'The handle is invalid'. Please help?
      Thank you in advance!
    • MazeM
      By MazeM
      Hi
      here's another UDF for the serial port. It is very similar to CommAPI using kernel32.dll, but all code is packed into a single file without any dependencies, not even using WinAPI.au3. It differs from existing UDF that it doesn't allow a timeout when reading, instead it always returns immediately, either with the requested amount ob bytes read or with a failure status. And of course there is a function provided to query the amount of available bytes in the receive buffer. The reason behind this design decision: You can do 1000 other things in the main loop while checking from time to time if enough data bytes arrived. There's no point to block the program waiting for the serial port.
      It is currently a work-in-progress, as I didn't test all functions yet. The code was developed and tested on Windows 7 64 bit.  The ComUDF-Tests.au3 shows some tests and basic usage of the UDF. Maybe there's no reason to use this UDF, given the existence of the others UDFs, but I did it to get to know DllCall better - I use structs no only to pass but also to get data back (I don't use the array returned by DllCall to read that data, unless required). You're welcome to test it on older and newer Windows versions.
      Here's a list of the implemented functions:
      ; _ComListPorts ; _ComOpenPort ; _ComSetTimeouts ; _ComClosePort ; ; _ComSetBreak ; _ComClearBreak ; _ComGetInputcount ; _ComGetOutputcount ; _ComClearOutputBuffer ; _ComClearInputBuffer ; ; _ComSendByte ; _ComReadByte ; _ComSendBinary ; _ComReadBinary ; ; _ComSendChar ; _ComReadChar ; _ComSendCharArray ; _ComReadCharArray ; _ComSendString ; _ComReadString ; ; __ComClearCommError ; __PurgeComm Maze
       
      ComUDF.au3
      ComUDF-Tests.au3
    • junkew
      By junkew
      Since W8.1 (actually IE 11 with W7 will work also) microsoft has a Javascript runtime that can be called from scripting languages
      As shown in this example from C++: https://iobservable.net/blog/2013/11/12/introduction-to-jsrt/
      By loading either JSCRIPT9.DLL or CHAKRA.DLL you can embed ECMA JavaScript in your application
      And implemented here in AutoHotKey https://autohotkey.com/boards/viewtopic.php?f=6&t=5739
      Triggered by other threads: 
      https://www.autoitscript.com/forum/topic/185883-accessing-autoit-variables/ https://iobservable.net/blog/2013/11/12/introduction-to-jsrt/ https://www.autoitscript.com/forum/topic/184824-chakracore-udf-executing-javascript-in-autoit/ http://eclipsesource.com/blogs/2016/04/06/getting-started-with-microsoft-chakracore/
        This code is almost working but unfortunately not with the expected output. Someone seeing what is wrong? 
      It runs completely after fixes of DanyFirex 
       
      ;~ https://iobservable.net/blog/2013/11/ ;~ Should work on all windows versions with IE11 #AutoIt3Wrapper_UseX64=N #Region enum JsErrorCode : unsigned int Enum $JsNoError = 0, _ $JsErrorCategoryUsage = 0x10000, _ $JsErrorInvalidArgument, _ $JsErrorNullArgument, _ $JsErrorNoCurrentContext, _ $JsErrorInExceptionState, _ $JsErrorNotImplemented, _ $JsErrorWrongThread, _ $JsErrorRuntimeInUse, _ $JsErrorBadSerializedScript, _ $JsErrorInDisabledState, _ $JsErrorCannotDisableExecution, _ $JsErrorHeapEnumInProgress, _ $JsErrorArgumentNotObject, _ $JsErrorInProfileCallback, _ $JsErrorInThreadServiceCallback, _ $JsErrorCannotSerializeDebugScript, _ $JsErrorAlreadyDebuggingContext, _ $JsErrorAlreadyProfilingContext, _ $JsErrorIdleNotEnabled, _ $JsErrorCategoryEngine = 0x20000, _ $JsErrorOutOfMemory, _ $JsErrorCategoryScript = 0x30000, _ $JsErrorScriptException, _ $JsErrorScriptCompile, _ $JsErrorScriptTerminated, _ $JsErrorScriptEvalDisabled, _ $JsErrorCategoryFatal = 0x40000, _ $JsErrorFatal ;~ }JsErrorCode; #EndRegion enum JsErrorCode : unsigned int #Region typedef enum JsRuntimeVersion Enum $JsRuntimeVersion10 = 0, $JsRuntimeVersion11 = 1 #EndRegion typedef enum JsRuntimeVersion ; Create callback function. Local $hPrintf = DllCallbackRegister("_printf", "long", "ptr;bool;ptr;ushort;ptr") Local $hJSRuntime = DllOpen("c:\windows\system32\jscript9.dll") $JsRuntimeAttributeNone = 0x00000000 ;~ #RequireAdmin Example() Func Example() Local $script = "native.printf('hello world')" ;~ Local $script = "native.printf('number=%#x string=%s\n', 255, 'test')" ;~ Local $script = "(()=>{return 'Hello world!';})()" ;~ Local $script = "var x='helloworld'; return x;" ;~ Local $script = "var x=10;" & @CRLF & "var y=11;" ;~ Local $script = "(42);" ;~ Local $script = "(" & @CRLF ;~ $script=$script & "host.echo(JSON.stringify({foo:'bar'}));)" & @CRLF ;~ $script=$script & "42 // The script's result :) "& @CRLF ;~ $script=$script & ")"& @CRLF ;~ $script=$script & "class Host {"& @CRLF ;~ $script=$script & " echo(s) {"& @CRLF ;~ $script=$script & " MsgBox %s%"& @CRLF ;~ $script=$script & " }"& @CRLF ;~ $script=$script & "}"& @CRLF Local $aResult Local $runtime Local $context ;~ // Create a runtime ;~ JsCreateRuntime(JsRuntimeAttributeNone, nullptr, &runtime); $runtime = _JsCreateRuntime($JsRuntimeAttributeNone, 0, $runtime) ; ;~ // Create an execution context. ;~ JsCreateContext(runtime, &context); $context = _JsCreateContext($runtime, $context) ;~ // Now set the current execution context. ;~ JsSetCurrentContext(context); _JsSetCurrentContext($context) ; ; Get the Global object for adding stuff ;~ JsGetGlobalObject(&global); Local $global $global = _JsGetGlobalObject($global) ;~ JsPropertyIdRef nativeProp; ;~ JsGetPropertyIdFromName(L"native", &nativeProp); Local $nativeProp $nativeProp = _JsGetPropertyIdFromName("native", $nativeProp) ;~ JsValueRef nativeObj; ;~ JsCreateObject(&nativeObj); Local $nativeObj $nativeObj = _JsCreateObject($nativeObj) ;~ JsPropertyIdRef printfProp; ;~ JsGetPropertyIdFromName(L"printf", &printfProp); Local $printfProp $printfProp = _JsGetPropertyIdFromName("printf", $printfProp) ;~ JsValueRef printfFunc; ;~ JsCreateFunction(PrintFormat, nullptr, &printfFunc); Local $printfFunc $printfFunc = _JsCreateFunction(DllCallbackGetPtr($hPrintf), 0, $printfFunc) ;~ JsSetProperty(nativeObj, printfProp, printfFunc, true); _JsSetProperty($nativeObj, $printfProp, $printfFunc, True) ;~ JsSetProperty(global, nativeProp, nativeObj, true); _JsSetProperty($global, $nativeProp, $nativeObj, True) ;~ STDAPI_(JsErrorCode) JsCreateFunction( ;~ _In_ JsNativeFunction nativeFunction, ;~ _In_opt_ void *callbackState, ;~ _Out_ JsValueRef *function ;~ ); ; Get a JsValueRef for our Host object ;~ hostRef := ToJsValue(Host) ;~ $aResult=DllCall($hJSRuntime, "int","JsVariantToValue", "ptr", &variant, "ptr*", valref) ; Pass our Host object to the script engine ;~ DllCall("jscript9\JsSetProperty", "ptr", globalObject, "ptr", hostPropertyId, "ptr", hostRef, "int", true) ;~ // Run the script. ;~ STDAPI_(JsErrorCode) JsRunScript( ;~ _In_z_ const wchar_t *script, ;~ _In_ JsSourceContext sourceContext, ;~ _In_z_ const wchar_t *sourceUrl, ;~ _Out_ JsValueRef *result ;~ ); Local $currentSourceContext = 1 ;~ JsRunScript(script.c_str(), currentSourceContext++, L"", &result); Local $result = "" Local $sourceURL = "" $aResult = DllCall($hJSRuntime, "int", "JsRunScript", "WSTR", $script, "UINT*", $currentSourceContext, "wstr", "dummysource.js", "WSTR*", $result) ConsoleWrite("Error 11: " & @error & @CRLF) If @error = 0 Then ConsoleWrite($aResult[0] & ";" & $aResult[1] & ";" & $aResult[2] & ";" & $aResult[3] & ";" & $aResult[4] & @CRLF) EndIf ;~ // Convert your script result to String in JavaScript redundant if your script returns a String ;~ JsValueRef resultJSString; ;~ STDAPI_(JsErrorCode) JsConvertValueToString( ;~ _In_ JsValueRef value, ;~ _Out_ JsValueRef *stringValue ;~ ); ;~ JsConvertValueToString(result, &resultJSString); ;~ $aResult=DllCall($hJSRuntime, "int", "JsConvertValueToString", "WSTR", $script, "long", 1, "WSTR*",0, "WSTR*", $result) ;~ consolewrite("Error 4: " & @error & @CRLF) ;~ if @error=0 Then ;~ consolewrite($aResult[0] & ";" & $aResult[1] & ";" & $aResult[2] & ";" & $aResult[3] & ";" & $aResult[4] & @CRLF) ;~ EndIf ;~ ;~ // Project script result back to C++. ;~ const wchar_t *resultWC; ;~ size_t stringLength; ;~ JsStringToPointer(resultJSString, &resultWC, &stringLength); ;~ wstring resultW(resultWC); ;~ cout << string(resultW.begin(), resultW.end()) << endl; ;~ system("pause"); ;~ // Dispose runtime ;~ JsSetCurrentContext(JS_INVALID_REFERENCE); ;~ JsDisposeRuntime(runtime); Return 0 ; EndFunc ;==>Example ; Create callback function. ;~ JsValueRef CALLBACK PrintFormat(JsValueRef callee, bool isConstructCall, JsValueRef *arguments, unsigned short argumentCount, void *callbackState) ;~ { ;~ const wchar_t *format; ;~ size_t length; ;~ JsStringToPointer(arguments[1], &format, &length); ;~ VARIANT variant; ;~ JsValueToVariant(arguments[2], &variant); ;~ const wchar_t *str; ;~ JsStringToPointer(arguments[3], &str, &length); ;~ wprintf(format, variant.intVal, str); ;~ return JS_INVALID_REFERENCE; ;~ } ;~ typedef _Ret_maybenull_ JsValueRef (CALLBACK * JsNativeFunction)( ;~ _In_ JsValueRef callee, ;~ _In_ bool isConstructCall, ;~ _In_ JsValueRef *arguments, ;~ _In_ unsigned short argumentCount ;~ ); Func _printf($callee, $isConstructCall, $arguments, $argumentCount, $callbackState) ConsoleWrite("there we are with " & $argumentCount & " arguments" & @CRLF) Local $tArgs = DllStructCreate("ptr JsValues[" & $argumentCount & "]", $arguments) ;~ STDAPI_(JsErrorCode) JsConvertValueToString( ;~ _In_ JsValueRef value, ;~ _Out_ JsValueRef *stringValue ;~ ); ;~ JsConvertValueToString(result, &resultJSString); local $tresult $aResult=DllCall($hJSRuntime, "int", "JsConvertValueToString", "ptr", DllStructGetData($tArgs,1,2), "ptr*", $tresult) consolewrite("Error 4: " & @error & @CRLF) if @error=0 Then consolewrite( $aResult[0] & ";" & $aResult[1] & ";" & $aResult[2] & @CRLF) $tresult=$aresult[2] EndIf ;~ STDAPI_(JsErrorCode) JsValueToVariant( ;~ _In_ JsValueRef object, ;~ _Out_ VARIANT *variant ;~ ); ;~ Local $aResult = DllCall($hJSRuntime, "dword", "JsValueToVariant", "ptr", $arguments[0], "ptr*", 0) ;~ If @error Then Return SetError(3, 0, @error) ;~ If $aResult[0] <> 0 Then Return SetError(4, 0, $aResult[0]) ;~ consolewrite($aResult[2]) Local $aResult = DllCall($hJSRuntime, "dword", "JsStringToPointer", "ptr", $tResult, "ptr*", 0, "int*", 0) If @error Then Return SetError(3, 0, @error) If $aResult[0] <> 0 Then Return SetError(4, 0, $aResult[0]) Local $tString = DllStructCreate("wchar string["&$aResult[3]&"]", $aResult[2]) consolewrite("+Parameter: " & $tString.string & @CRLF) Return 0 EndFunc ;==>_printf ;~ typedef void *JsRuntimeHandle; ;~ // Create a runtime. ;~ Edge mode signature STDAPI_(JsErrorCode) JsCreateRuntime( ;~ _In_ JsRuntimeAttributes attributes, ;~ _In_opt_ JsThreadServiceCallback threadService, ;~ _Out_ JsRuntimeHandle *runtime); ;~ Legacy mode signature ;~ STDAPI_(JsErrorCode) JsCreateRuntime( ;~ _In_ JsRuntimeAttributes attributes, ;~ _In_ JsRuntimeVersion version, ;~ _In_opt_ JsThreadServiceCallback threadService, ;~ _Out_ JsRuntimeHandle *runtime ;~ ); ;~ $runtime=_JsCreateRuntime(JsRuntimeAttributeNone, 0, $runtime); Func _JsCreateRuntime($JsRuntimeAttributeNone, $JSRuntimeVersion, $runtime) $aResult = DllCall($hJSRuntime, "int", "JsCreateRuntime", "int", $JsRuntimeAttributeNone, "int", $JSRuntimeVersion, "ptr", 0, "ptr*", $runtime) If @error Then Return SetError(1, @error, 0) Return $aResult[4] EndFunc ;==>_JsCreateRuntime ;~ // Edge mode signature ;~ STDAPI_(JsErrorCode) JsCreateContext( ;~ _In_ JsRuntimeHandle runtime, ;~ _Out_ JsContextRef *newContext); ;~ // Legacy mode signature ;~ STDAPI_(JsErrorCode) JsCreateContext( ;~ _In_ JsRuntimeHandle runtime, ;~ _In_ IDebugApplication *debugApplication, ;~ _Out_ JsContextRef *newContext ;~ ); ;~ JsCreateContext(runtime, &context); Func _JsCreateContext($runtime, $context) $aResult = DllCall($hJSRuntime, "int", "JsCreateContext", "ptr", $runtime, "ptr", 0, "ptr*", $context) If @error Then Return SetError(1, @error, 0) Return $aResult[3] EndFunc ;==>_JsCreateContext ;~ STDAPI_(JsErrorCode) JsSetCurrentContext( ;~ _In_ JsContextRef context ;~ ); ;~ JsSetCurrentContext(context); Func _JsSetCurrentContext($context) $aResult = DllCall($hJSRuntime, "int", "JsSetCurrentContext", "ptr", $context) If @error Then Return SetError(1, @error, 0) Return $JsNoError EndFunc ;==>_JsSetCurrentContext ; Get the Global object for adding stuff ;~ STDAPI_(JsErrorCode) JsGetGlobalObject( ;~ _Out_ JsValueRef *globalObject ;~ ); ;~ JsValueRef global; ;~ JsGetGlobalObject(&global); Func _JsGetGlobalObject($global) $aResult = DllCall($hJSRuntime, "int", "JsGetGlobalObject", "ptr*", $global) If @error Then Return SetError(1, @error, 0) Return $aResult[1] EndFunc ;==>_JsGetGlobalObject ; Get a property ID for the name "host" ;~ STDAPI_(JsErrorCode) JsGetPropertyIdFromName( ;~ _In_z_ const wchar_t *name, ;~ _Out_ JsPropertyIdRef *propertyId ;~ ); ;~ DllCall("jscript9\JsGetPropertyIdFromName", "wstr", "host", "ptr*", hostPropertyId) ;~ local $hostPropertyID ;~ $aResult=DllCall($hJSRuntime, "int","JsGetPropertyIdFromName", "wstr", "host", "ptr*", $hostPropertyId) ;~ consolewrite("Error 5: " & @error & @CRLF) ;~ if @error=0 Then ;~ consolewrite($aResult[0] & ";" & $aResult[1] & ";" & $aResult[2] & @CRLF) ;~ EndIf ;~ JsPropertyIdRef nativeProp; ;~ JsGetPropertyIdFromName(L"native", &nativeProp); Func _JsGetPropertyIdFromName($propname, $nativeProp) $aResult = DllCall($hJSRuntime, "int", "JsGetPropertyIdFromName", "wstr", $propname, "ptr*", $nativeProp) If @error Then Return SetError(1, @error, 0) Return $aResult[2] EndFunc ;==>_JsGetPropertyIdFromName ;~ STDAPI_(JsErrorCode) JsCreateObject( ;~ _Out_ JsValueRef *object ;~ ); ;~ JsValueRef nativeObj; ;~ JsCreateObject(&nativeObj); Local $nativeObj Func _JsCreateObject($JSRTobject) $aResult = DllCall($hJSRuntime, "int", "JsCreateObject", "ptr*", $JSRTobject) If @error Then Return SetError(1, @error, 0) Return $aResult[1] EndFunc ;==>_JsCreateObject ;~ STDAPI_(JsErrorCode) JsCreateFunction( ;~ _In_ JsNativeFunction nativeFunction, ;~ _In_opt_ void *callbackState, ;~ _Out_ JsValueRef *function ;~ ); Func _JsCreateFunction($fncCallBackPtr, $callbackState, $fncVar) $aResult = DllCall($hJSRuntime, "int", "JsCreateFunction", "ptr", $fncCallBackPtr, "ptr*", $callbackState, "ptr*", $fncVar) If @error Then Return SetError(1, @error, 0) Return $aResult[3] EndFunc ;==>_JsCreateFunction ;~ JsSetProperty(nativeObj, printfProp, printfFunc, true); ;~ STDAPI_(JsErrorCode) JsSetProperty( ;~ _In_ JsValueRef object, ;~ _In_ JsPropertyIdRef propertyId, ;~ _In_ JsValueRef value, ;~ _In_ bool useStrictRules ;~ ); Func _JsSetProperty($Obj, $Prop, $Func, $val) ; $aResult = DllCall($hJSRuntime, "int", "JsSetProperty", "ptr", $Obj, "ptr", $Prop, "ptr", $Func, "int", $val) If @error Then Return SetError(1, @error, 0) EndFunc ;==>_JsSetProperty