![]() |
Common Language Extension(CLE) |
|||
Here presents a new method for lua calling c++. A function “Add” is defined in c++ which returns the sum of two input integers. The function also calls lua method “Show” to print the result. Using cle to developed c++ extension, c++ externsion should be compiled into a sharelib which exports two functions StarCoreService_Init and StarCoreService_Term. There are four steps: 1. Create service. 2. Create interface object, and defines a new function “Add” of it. 3. Write function code of Add. 4. Set function address of Add to object’ function definition.
#include "vsopenapi.h"
static class ClassOfSRPInterface *SRPInterface;
//--Step 3 : Add function body
static VS_INT32 Add(void *Object,VS_INT32 x,VS_INT32 y)
{
//--Callback script function
SRPInterface -> ScriptCall(Object,NULL,"Show","(i)",x+y);
return
x + y;
}
VS_BOOL StarCoreService_Init(class ClassOfStarCore
*starcore)
{
void
*AtomicClass,*Add_AtomicFunction;
class
ClassOfBasicSRPInterface *BasicSRPInterface;
//--Step
1 : Create service
BasicSRPInterface
= starcore ->GetBasicInterface();
BasicSRPInterface
->CreateService("","AddFunctionService",NULL,"123",0,0,0,0,0,0);
//--Step 2 : Create object and defines a new function
“Add”
SRPInterface
= BasicSRPInterface
->GetSRPInterface("AddFunctionService","root","123");
AtomicClass
= SRPInterface
->CreateAtomicObjectSimple("TestItem","TestClass",NULL,NULL,NULL);
Add_AtomicFunction
= SRPInterface
->CreateAtomicFunctionSimple(AtomicClass,"Add","VS_INT32
Add(VS_INT32 x,VS_INT32 y);",NULL,NULL,VS_FALSE,VS_FALSE);
//--Step 4 : Set function address to Add function
SRPInterface
-> SetAtomicFunction(Add_AtomicFunction,(void *)Add);
return
VS_TRUE;
}
void StarCoreService_Term(class ClassOfStarCore
*starcore)
{
SRPInterface
-> Release();
return;
}
Compile into sharelibrary, may be named “AddFunctionService.dll”.
For lua code calls the above sharelib, there are three steps; 1. Init cle, create service group,import sharelibrary, and create service. 2. Create Instance of object “TestClass” defined in sharelibrary. 3. Call function “Add”.
require "libstarcore"
--Step 1 : Init cle, create service
group,import sharelibrary, and
create service.
Service=libstarcore._InitSimple("test","123",0,0,"AddFunctionService.dll");
--Step 2: Create Instance of object “TestClass”
defined in sharelibrary.
a = Service.TestClass:_New();
--Step 3: call function “Add”
function a:Show(
print("print from lua call back "..
end
print("Add returns : "..a:Add(12,34))
Service._ServiceGroup:_ClearService()
libstarcore._ModuleExit()
Run : starapp -e lua_call.lua |
| examples code download |
| Copywright (C) 2005 www.SRPLab.com(Star-River Platform Lab.) All Rights Reserved | Email:support@srplab.com |