Click here to Skip to main content
15,879,535 members
Articles / Programming Languages / C++

Enhanced Transparent Flash Control in C++

Rate me:
Please Sign up or sign in to vote.
4.90/5 (15 votes)
28 Apr 2011CPOL4 min read 71.3K   3.8K   55   20
OLE container implementation for hosting a Flash Player control using C++, with support for calls and callbacks between C++ and Flash ActionScript.
EnhancedFlashControl screen shot

Introduction

This article is based on the excellent article written by Makarov Igor. It extends the functionality with support for calls and callbacks between C++ and Flash ActionScript.

Background

Because I was looking for some (C++) code to play a Shock Wave Flash (.swf) file with ActionScript, I found the above referenced article. However, it did not have support for calls and callbacks. There's plenty of documentation on the Flash ExternalInterface, but I found it hard to find a working example. So I added it and thought it may be useful to others as well.

Using the Code

Since Flash uses XML for marshalling parameters back and forth on the ExternalInterface, I decided to use the TinyXML library. It is included in the sample code.

Part 1. Flash ActionScript

Let's start with the ActionScript part. In the file "HelloWorld.as", there is a line that tells the ExternalInterface of Flash to register a callback:

Java
// Register a callback on the Flash External Interface that can
// be called from C++ (or any other container, e.g. javascript)
ExternalInterface.addCallback("setButtonText", onSetButtonText);

The above code registers the ActionScript function with the name onSetButtonText, which can be called by the name setButtonText from e.g., JavaScript (if the container would be a web browser) or C++ (in this example).

The function onSetButtonText simply sets the text of the button, purely for demonstration purposes:

JavaScript
public function onSetButtonText(arg:String):String {
    button.setLabel(arg);
    return "OK";
}

Each time the user clicks the button in the Flash ActionScript, the mouseDownHandler is called. For animation, it changes the x and y coordinates and it calls count to get new text for the button:

JavaScript
private function mouseDownHandler(event:MouseEvent):void {
    button.x += 1;
    button.y += 1;
    button.setLabel(count());
}

Below is an example of how to call the Flash ExternalInterface from ActionScript. It calls the addNumbers function. Handling this call in C++ code is described in the next paragraphs.

JavaScript
// Demonstration on how to use the Flash ExternalInterface
// This example calls the function 'addNumbers' in the C++ container app
public function count():String {
    // calls the external function "addNumbers" 
    // (in JavaScript, or container projector)
    // passing two parameters, and assigning that function's result 
    // to the variable "counter"
    ExternalInterface.marshallExceptions = true;
    try {
        counter = ExternalInterface.call("addNumbers", counter, 1);
        return String(counter);
    }
    catch(e:Error) {
        return e.toString();
    }
    return String("Error");
}

Part 2. Event Handling in the C++ Code

As mentioned before, the code is re-used. The function CFlashWnd::Invoke has been enhanced so that it understands the events dispatched from Flash. If all parameters are OK, it calls the FlashCall method.

C++
HRESULT STDMETHODCALLTYPE CFlashWnd::Invoke(...)
{
    if (wFlags == DISPATCH_METHOD)
    {
        switch (dispIdMember)          
        {          
        case 0xc5: // FlashCall (from ActionScript)
            if (pDispParams->cArgs != 1 || pDispParams->rgvarg[0].vt != VT_BSTR) 
                return E_INVALIDARG;
            return this->FlashCall(pDispParams->rgvarg[0].bstrVal);

The CFlashWnd::FlashCall then does the dirty work, i.e., unmarshalling the XML. Parsing the request is done by the call to the Tiny XML library function doc.Parse. Flash passes the call details in an XML <invoke> element. It is looked up by hDoc.FirstChildElement("invoke"). The name of the called function is specified in attribute "name" of the <invoke> element. It is looked up by a call to QueryStringAttribute. If all information is OK, the whole element tree is passed on to the addNumbers method.

C++
// Handle a call from Flash ActionScript (in .swf file)
HRESULT STDMETHODCALLTYPE CFlashWnd::FlashCall(_bstr_t request)
{
    HRESULT hr = S_FALSE;

    if (m_lpControl != NULL)
    {
        TiXmlDocument doc;
        const char *c_str = _com_util::ConvertBSTRToString(request);
        // Parse the XML string to into an XML doc
        doc.Parse(c_str);
        delete[] c_str;

        TiXmlHandle hDoc(&doc);
        // Look for the invoke element
        TiXmlElement *pInvokeElement = hDoc.FirstChildElement("invoke").Element();
        if (pInvokeElement != NULL)
        {
            std::string functionName;
            int result = pInvokeElement->QueryStringAttribute("name", &functionName);
            if (result == 0)
            {
                if (functionName == "addNumbers")
                {
                    // Finally, handle the request
                    hr = addNumbers(pInvokeElement);
                }
            }
        }
    }
    return hr;
}

The above code shows a very simple way to handle function call requests from Flash ActionScript. Feel free to improve this if you wish to handle more calls. After all, this is just demonstrating the basics of the mechanism.

Part 3. Returning the Result from C++ to ActionScript

So CFlashWnd::FlashCall is now capable of decoding the called function name. Now, let's take a look at how to decode the function arguments and pass the function result (return value) back to the Flash object (ExternalInterface) as a number:

C++
HRESULT CFlashWnd::addNumbers(TiXmlElement *pInvokeElement)
{
    HRESULT hr = E_INVALIDARG; // Default result if something is wrong

    TiXmlElement *pArgumentElement = pInvokeElement->FirstChildElement("arguments");
    if (pArgumentElement != NULL)
    {
        TiXmlElement *pArgumentNumber = 
		pArgumentElement->FirstChildElement("number");
        if (pArgumentNumber != NULL)
        {
            int number1 = atoi(pArgumentNumber->GetText());
            pArgumentNumber = pArgumentNumber->NextSiblingElement("number");
            if (pArgumentNumber != NULL)
            {
                int number2 = atoi(pArgumentNumber->GetText());
                WCHAR result[80];
                _snwprintf_s(result, 80, 80, 
		L"<number>%d</number>", number1 + number2);
                // Set the return value in the Flash object (ExternalInterface)
                hr = m_lpControl->SetReturnValue(result);
            }
        }
    }
    return hr;
}

The above code shows how to pass the result back to Flash by calling SetReturnValue on the ActiveX interface. It also shows how to use the function from the Tiny XML library to get the required argument values.

Part 4. Calling ActionScript from C++

A simple example of how to call ActionScript from C++ is shown below. Note that ExternalInterface.addCallback must have been called in the ActionScript, see part 1, or otherwise things will fail!

C++
BSTR _result = m_lpControl->CallFunction(L"<invoke name=\"setButtonText\" 
returntype=\"xml\"><arguments><string>Click me!</string></arguments></invoke>");

Building the Flash ActionScript

To compile the .as file into an .swf file that can be played by the Flash player, I used the free mxmlc compiler from Adobe. You can download it from their site.

To build it as part of the Visual Studio project, add a custom build rule:

"F:\Program Files\Adobe\Flex_SDK_4.0\bin\mxmlc.exe" --show-actionscript-warnings=true 
--strict=true -static-link-runtime-shared-libraries 
-output $(OutDir)\$(InputName).swf $(InputName).as 

CustomBuild.gif

Acknowledgements

Special thanks to the authors of:

Without them, it would have been a lot harder to write the code!

Legal Stuff

Unfortunately, we live in a world where these kind of messages are necessary...

This article and source code have been provided to you for use as you see fit, without any warranty! This article and source code only demonstrate the basic principles and should not be used in situations that can do harm to people, animals or cause risks of any kind. Please use it at your own risk, not mine. I cannot be held responsible, you have been warned.

Sorry for that, I hope it doesn't sound too offensive. Because, after all, coding should be fun!

History

  • 8th April, 2011: Initial post

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)


Written By
Software Developer (Senior) LSO - Lieshout Software Ontwikkeling
Netherlands Netherlands
Fred is an experienced software engineer with in-depth knowledge of software design, coding and testing. He is interested in the analysis, requirements and design phases in particular, but still enjoys ‘getting his hands dirty’ with software programming. Favorite programming languages are C, C++, C# and Java.

LinkedIn: profile

Comments and Discussions

 
QuestionHas anybody tried this with the new 64 bit flash? Pin
Member 115979935-Jun-15 22:40
Member 115979935-Jun-15 22:40 
Questionfailure during conversion to COFF: file invalid or corrupt Pin
Tricube2-Jun-13 20:13
Tricube2-Jun-13 20:13 
AnswerRe: failure during conversion to COFF: file invalid or corrupt Pin
Fred van Lieshout3-Jun-13 9:39
Fred van Lieshout3-Jun-13 9:39 
GeneralMy vote of 5 Pin
flyhigh26-Oct-12 3:30
professionalflyhigh26-Oct-12 3:30 
GeneralRe: My vote of 5 Pin
Fred van Lieshout26-Oct-12 7:58
Fred van Lieshout26-Oct-12 7:58 
QuestionGood job Pin
wshcdr16-Oct-12 19:59
wshcdr16-Oct-12 19:59 
AnswerRe: Good job Pin
Fred van Lieshout17-Oct-12 10:21
Fred van Lieshout17-Oct-12 10:21 
QuestionDoesn't compile Pin
Michael Haephrati29-Sep-12 6:02
professionalMichael Haephrati29-Sep-12 6:02 
AnswerRe: Doesn't compile Pin
Fred van Lieshout1-Oct-12 5:25
Fred van Lieshout1-Oct-12 5:25 
AnswerRe: Doesn't compile Pin
Michael Haephrati21-Sep-17 10:19
professionalMichael Haephrati21-Sep-17 10:19 
QuestionIs it possible to wrap it all up into one executable? Pin
alikim2-Dec-11 1:17
alikim2-Dec-11 1:17 
AnswerRe: Is it possible to wrap it all up into one executable? Pin
Fred van Lieshout4-Dec-11 1:42
Fred van Lieshout4-Dec-11 1:42 
GeneralRe: Is it possible to wrap it all up into one executable? Pin
alikim4-Dec-11 2:15
alikim4-Dec-11 2:15 
Question64 bit flash Pin
Member 830542810-Oct-11 5:54
Member 830542810-Oct-11 5:54 
AnswerRe: 64 bit flash Pin
Fred van Lieshout10-Oct-11 6:32
Fred van Lieshout10-Oct-11 6:32 
GeneralRe: 64 bit flash Pin
Member 830542810-Oct-11 7:09
Member 830542810-Oct-11 7:09 
GeneralRe: 64 bit flash Pin
Fred van Lieshout10-Oct-11 7:25
Fred van Lieshout10-Oct-11 7:25 
GeneralRe: 64 bit flash Pin
Mosc3-Jun-12 22:47
Mosc3-Jun-12 22:47 
GeneralMy vote of 5 Pin
Amro Ibrahim20-Apr-11 1:50
Amro Ibrahim20-Apr-11 1:50 
GeneralRe: My vote of 5 Pin
Fred van Lieshout26-Apr-11 20:43
Fred van Lieshout26-Apr-11 20:43 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.