Version 1 (modified by 14 years ago) ( diff ) | ,
---|
Defining interfaces in C++
Think of a name for the component. We'll use "Position" in this example; replace it with your chosen name in all the filenames and code samples below.
Create the file simulation2/components/ICmpPosition.h
:
/* Copyright (C) 2010 Wildfire Games. * ...the usual copyright header... */ #ifndef INCLUDED_ICMPPOSITION #define INCLUDED_ICMPPOSITION #include "simulation2/Interface.h" ...any other forward declarations and includes you might need... /** * Documentation to describe what this interface and its associated component types are * for, and roughly how they should be used. */ class ICmpPosition : public IComponent { public: /** * Documentation for each method. */ virtual int DoWhatever(int x, int y) = 0; ... DECLARE_INTERFACE_TYPE(Position) }; #endif // INCLUDED_ICMPPOSITION
This defines the interface that C++ code will use to access components.
Create the file simulation2/components/ICmpPosition.cpp
:
/* Copyright (C) 2010 Wildfire Games. * ...the usual copyright header... */ #include "precompiled.h" #include "ICmpPosition.h" #include "simulation2/InterfaceScripted.h" BEGIN_INTERFACE_WRAPPER(Position) DEFINE_INTERFACE_METHOD_2("DoWhatever", int, ICmpPosition, DoWhatever, int, int) ... END_INTERFACE_WRAPPER(Position)
This defines a JavaScript wrapper, so that scripts can access methods of components implementing that interface.
This wrapper should only contain methods that are safe to access from simulation scripts: they must not crash, they must return deterministic results, etc. Methods that are intended for use solely by C++ should not be listed here.
Interface method script wrappers
Interface methods are defined with the macro:
DEFINE_INTERFACE_METHOD_
NumberOfArguments("
MethodName",
ReturnType, ICmpPosition,
MethodName,
!ArgType0,
!ArgType1, ...)
corresponding to the C++ method ReturnType ICmpPosition::
MethodName(
!ArgType0,
!ArgType1, ...)
There's a small limit to the number of arguments that are currently supported - if you need more, first try to save yourself some pain by using fewer arguments, otherwise you'll need to add a new macro into simulation2/InterfaceScripted.h
and increase MAX_ARGS
in scriptinterface/NativeWrapperDecls.h
. (Not sure if anything else needs changing.)
To convert types between C++ and JS, ToJSVal<ReturnType>
and FromJSVal<ArgTypeN>
must be defined, as below.
Script type conversions
...