MakeInstance 复制链接
简述
将TSL函数生成C的函数指针。如果需要将TSL函数输出为外部程序调用的函数指针,如C语言函数的指针,就可以通过MakeInstance来实现。
产生一个TSL函数的函数指针,Fun可以是TSL函数、类成员函数类型。
注:在该模式下,对于TSL函数一定要有类型声明,若没有类型声明,就无法去生成C语言的调用,所以一定要有类型声明。
声明语法:function TsfunName(p1:DataType;p2:Datetype;…):returnType;
Begin
//函数体
End;
如,声明一个天软函数:
function TSFunc(a:integer;b:integer):Double;
begin
return inttodate(a)-inttodate(b);
end;
生成函数指针:
f1:=MakeInstance(findfunction("TSFunc"));
目前makeinstance支持的返回类型仅支持数字浮点(单精度和双精度)和整数,用于各式回调支持。
MakeInstance(Fun:String|TFunction;[mode:”cdecl”/”stdcall”;Threadmode:Integer]):pointer
名称 类型 说明 Fun String|TFunction 可以是TSL函数,也可以是TSL类的成员函数。 Mode ”cdecl”/”stdcall” 可选参数,缺省调用方式采用cdecl模式,除win32外,其它环境无意义。
在win32下,由于系统的回调函数许多是stdcall的,因而也支持stdcall模式。
在Linx以及win64下,stdcall和cdecl的调用模式相同。 Threadmode Integer 可选参数,线程模式,缺省调用单线程模式
取值
线程模式
0
单线程模式
1
多线程单模
2
多线程多模
返回 pointer 函数的指针。等同于C语言中的函数指针,在C语言中可以直接进行调用。
c代码
#include <Windows.h>
#include <string>
using std::string;
extern "C" {
#include "TSSVRAPI.h"
}
using func = double(*)(int); //c++11
int main()
{
TObject* r = TSL_NewObject();
TObject* v = TSL_NewObject();
TObject* err = TSL_NewObject();
TSL_State* L = TS_GetGlobalL();
//重新定义TSL函数接口,并生成该函数的函数指针
string s = "f1:=MakeInstance(findfunction('TS_inttodate')); return f1;//对天软公用函数进行重新封装,声明接口输入输出的类型 function TS_inttodate(a:integer) :Double; begin return inttodate(a); end; ";
int ret = TSL_ScriptGo(L, s.c_str(),v);
if (ret == TSL_OK)
{
func inttodate;
inttodate = (func)TSL_AsInt64(v);
double re = inttodate(20220101);
printf("%lf\n", re);
}
else {
printf("TSL error");
}
}
执行结果: