TSL语言基础 > TSL语言基础 > 函数定义体和函数 > 外部交互扩展调用接口

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
参数
名称类型说明
FunString|TFunction可以是TSL函数,也可以是TSL类的成员函数。
Mode”cdecl”/”stdcall”可选参数,缺省调用方式采用cdecl模式,除win32外,其它环境无意义。
在win32下,由于系统的回调函数许多是stdcall的,因而也支持stdcall模式。
在Linx以及win64下,stdcall和cdecl的调用模式相同。
ThreadmodeInteger可选参数,线程模式,缺省调用单线程模式
取值 线程模式
0 单线程模式
1 多线程单模
2 多线程多模
返回pointer函数的指针。等同于C语言中的函数指针,在C语言中可以直接进行调用。
  • 范例
    c代码
    #include <Windows.h>
    #include <Windows.h>
    #include <string>
    using std::string;
    extern "C" {
    #include "TSSVRAPI.h"
    }
    typedef void(*fInterpPrepare)(TSL_State* L);
    typedef void(*fInitPubkrnl)(void);
    using func = double(*)(int); //c++11
    int main()
    {
    TSL_InterpInit();
    fInterpPrepare TSL_InterpPrepare = (fInterpPrepare)GetProcAddress(LoadLibraryA("TSLInterp.dll"), "TSL_InterpPrepare");
    fInitPubkrnl TSL_InitPubkrnl = (fInitPubkrnl)GetProcAddress(LoadLibraryA("tslkrnl.dll"), "TSL_InitPubkrnl");
    TSL_InitPubkrnl(); //初始tsl内核
    TObject* r = TSL_NewObject();
    TObject* v = TSL_NewObject();
    TObject* err = TSL_NewObject();
    TSL_State* L = TS_GetGlobalL();
    TSL_InterpPrepare(L); //初始化解析器
    //重新定义TSL函数接口,并生成该函数的函数指针
    string s = "f1:=MakeInstance(findfunction('TS_inttodate'));  return f1;//对天软公用函数进行重新封装,声明接口输入输出的类型  \r\nfunction TS_inttodate(a:integer) :Double;  \r\nbegin   \r\nreturn inttodate(a);  \r\nend; ";
    int ret = TSL_ScriptGo(L, s.c_str(), v); //执行tsl 获取tsl构造的函数指针
    if (ret == TSL_OK)
    {
     func inttodate;
     inttodate = (func)TSL_AsInt64(v);
     double re = inttodate(20220101);
     printf("%lf\n", re);
    }
    else {
     printf("TSL error");
    }
    }

    执行结果:
相关
FAQ/知识库链接