Dll
In some cases, the built-in functions in
Silk cannot do what we want, so we need to build and load Dll
(extension libraries) to extend Silk.
We can use the following built-in functions to load the Dll:
_loadlib(filename)_loadlib
can load the Dll into memory and return a Dll handle, filename is the
Dll filename with the path, the default path is the current directory.
//lib=_loadlib("SilkCommonLib64.dll");
lib=_loadlib("D:\\silk_test\\SilkCommonLib64.dll");
if(lib)
print("load dll ok");
_calllib(lib, function, parameters...)We
can use _calllib to call the function in the Dll, lib is the handle
returned by _loadlib, function is the name of function in the Dll,
and parameters is the parameter list of the function.
It will return an array which has the execution result, and return empty array if it fails.
func get_curdir()
{
curdir="./";
curfile=_getargv()[0];
slash="\\";
if(_fun("os_platform").find("WIN")<0)
slash="/";
pos=curfile.rfind(slash);
if(pos>=0)
curdir=curfile.substr(0,pos+1);
return curdir;
}
main()
{
filename=get_curdir()+"SilkCommonLib64.dll";//prepare the dll filename with the full path
lib=_loadlib(filename);//load the dll
if(lib)
{
ret=_calllib(lib,"base64_encode","Good morning!");//call the fucntion named base64_encode in Dll
if(ret)
{
base64Str=ret[0];//return an array with the results, only 1 result, we get the first one.
print(base64Str);
}
_freelib(lib);//release the dll
}
}
_freelib(lib)Use _freelib to release the Dll, lib is the handle returned by _loadlib.
Develop DllThe Dll can be developed and built with C/C++, and we need to follow the rules that Silk defines:
The C/C++ Dll project should inlcude the header file
silklib.h , which can receive the parameters that Silk pass, and return the results to Silk in parameters.
The following C/C++ code shows how to develop a Dll that Silk can use:
#include "silklib.h"
#define EXPORT __declspec(dllexport)
extern "C" {
EXPORT PARAMS* base64_encode(PARAMS* pParam) { //Silk will pass the data to dll through PARAMS
char *pBuff=NULL;
int nSize = 0;
if (pParam)
{
if (pParam->nCount == 1)//Silk pass data through a parameter
{
if (pParam->pParams[0].nType == PARAM_STR)//the data type is String
{
if (pParam->pParams[0].nSize > 0)
{
nSize = pParam->pParams[0].nSize;
pBuff = new char[nSize+1];
pBuff[nSize] = 0;
sprintf(pBuff, "%s", (char*)(pParam->pParams[0].pValue));//put data into pBuff
}
}
}
}
if (pBuff)
{
string str = CommonLib::base64_encode(pBuff, nSize);//encode the data with base64
delete pBuff;
PARAMS* pRetParam = create_params(1);//Only 1 result, so create PARAMS with 1, can be more than 1
add_string(pRetParam, str.c_str(), str.size());//add result in PARAMS, continue adding if more...
return pRetParam;//return the result to Silk
}
return NULL;
}
}
Please refer to
Dll Sample for details.