Advertisement
snake5

SGScript - basic C++ binding [WIP]

Jun 15th, 2013
257
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.90 KB | None | 0 0
  1. #include <stdio.h>
  2. #include <string>
  3.  
  4. #include "cppbind.h"
  5.  
  6.  
  7. class Account
  8. {
  9. public:
  10.     int coins;
  11.     int numtransactions;
  12.     std::string name;
  13.    
  14.     Account() : coins( 0 ), numtransactions( 0 ){}
  15.    
  16.     int Add( SGS_CTX )
  17.     {
  18.         int orig = coins;
  19.         sgs_Integer I;
  20.         if( sgs_StackSize( C ) != 2 ||
  21.             !sgs_ParseInt( C, 1, &I ) )
  22.             return sgs_Printf( C, SGS_WARNING, "unexpected arguments" );
  23.         coins += (int) I;
  24.         numtransactions++;
  25.         printf( "Transaction #%04d | before=%d after=%d\n",
  26.             numtransactions, orig, coins );
  27.         return 0;
  28.     }
  29. };
  30.  
  31. SGS_DECLARE_IFACE( Account );
  32. SGS_METHOD_WRAPPER( Account, Add );
  33. SGS_BEGIN_GENERIC_GETINDEXFUNC( Account )
  34.     SGS_GGIF_METHOD( Account, Add )
  35.     SGS_GGIF_CUSTOM( Account, coins, sgs_PushInt(C,item->coins) )
  36.     SGS_GGIF_CUSTOM( Account, name, sgs_PushString(C,item->name.c_str()) )
  37.     SGS_GGIF_CUSTOM( Account, transaction_count, sgs_PushInt(C,item->numtransactions) )
  38. SGS_END_GENERIC_GETINDEXFUNC;
  39. SGS_BEGIN_GENERIC_SETINDEXFUNC( Account )
  40.     SGS_GSIF_CUSTOM( Account, name,
  41.         char* str; sgs_SizeVal strlen;
  42.         if( !sgs_ParseString( C, 1, &str, &strlen ) )
  43.             return SGS_EINVAL;
  44.         item->name.assign( str, strlen );
  45.     )
  46. SGS_END_GENERIC_SETINDEXFUNC;
  47. SGS_GENERIC_DESTRUCTOR( Account );
  48. SGS_DEFINE_IFACE( Account )
  49.     SGS_IFACE_ENTRY( GETINDEX, SGS_GETINDEXNAME( Account ) ),
  50.     SGS_IFACE_ENTRY( SETINDEX, SGS_SETINDEXNAME( Account ) ),
  51.     SGS_IFACE_ENTRY( DESTRUCT, SGS_DTORNAME( Account ) ),
  52. SGS_DEFINE_IFACE_END;
  53. SGS_DEFINE_EMPTY_CTORFUNC( Account );
  54.  
  55.  
  56. const char* code =
  57. "\n\
  58. a = Account();\n\
  59. a.Add( 1337 );\n\
  60. print 'reading from property: ' $ a.coins $ '\\n';\n\
  61. a.name = 'special';\n\
  62. printvars( a.name, a.transaction_count, a.coins );\n\
  63. ";
  64.  
  65. int main( int argc, char* argv[] )
  66. {
  67.     printf( "CPP binding test...\n" );
  68.    
  69.     SGS_CTX = sgs_CreateEngine();
  70.    
  71.     SGS_REGISTER( Account );
  72.    
  73.     sgs_ExecString( C, code );
  74.    
  75.     sgs_DestroyEngine( C );
  76.    
  77.     return 0;
  78. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement