![]() |
Common Language Extension(CLE) |
|||
Here presents a new method for python calling c++. A function “Add” is defined in c++ which returns the sum of two input integers. The function also calls python 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 python 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”.
import starpy
--Step 1 : Init cle, create service
group,import sharelibrary, and
create service.
Service=starpy._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”
def a_Show(self,
print("print from python call back ",
a.Show = a_Show;
print("Add returns : ",a.Add(12,34))
Service._ServiceGroup._ClearService()
starpy._ModuleExit()
Run : starapp -e python_call.py?script=python, or python python_call.py |
| examples code download |
| Copywright (C) 2005 www.SRPLab.com(Star-River Platform Lab.) All Rights Reserved | Email:support@srplab.com |