#include "mlp_c.h" #include "dlfcn.h" mlp_c_function::mlp_c_function(mlp_context *ctx, mlp_runtime *rt, mlp_library *lib, mlp_type rtype, const char *name, mlp_prototype proto) : mlp_function(ctx, rt, lib, rtype, name, proto), cif(NULL), entrypoint(NULL) { ctx->clear_error() ; entrypoint = ((mlp_c_library *)lib)->_load_entrypoint(ctx, name) ; if (entrypoint == NULL){ return ; } CInvContext *cic = (CInvContext *)ctx->get_runtime_data(rt) ; char r = mlp_c_type2cinvformat(rtype) ; std::string p ; for (mlp_prototype::iterator i = proto.begin() ; i != proto.end() ; i++){ p += mlp_c_type2cinvformat(*i) ; } cif = cinv_function_create(cic, CINV_CC_CDECL, &r, p.c_str()) ; if (cif == NULL){ ctx->set_error(MLP_FUNCTION_ERROR, "Can't locate entrypoint '%s' in library '%s': %s\n", name, lib->get_name(ctx), cinv_context_geterrormsg(cic)) ; return ; } } mlp_c_function::~mlp_c_function(){ } mlp_value *mlp_c_function::call(mlp_context *ctx, mlp_arguments args){ ctx->clear_error() ; CInvContext *cic = (CInvContext *)ctx->get_runtime_data(rt) ; void *_rtype = mlp_c_allocate_cinv_type(rtype) ; void **_args = (void **)malloc(args.size() * sizeof(void *)) ; for (int i = 0 ; i < args.size() ; i++){ _args[i] = mlp_c_allocate_cinv_value(proto[i], &(args[i])) ; } cinv_status_t rc = cinv_function_invoke(cic, cif, entrypoint, _rtype, _args) ; for (int i = 0 ; i < args.size() ; i++){ free(_args[i]) ; } free(_args) ; if (rc == CINV_ERROR){ ctx->set_error(MLP_FUNCTION_ERROR, "Can't call function '%s': %s\n", this->name.c_str(), cinv_context_geterrormsg(cic)) ; free(_rtype) ; return NULL ; } mlp_value *ret = mlp_c_allocate_mlp_value(rtype, _rtype) ; free(_rtype) ; return ret ; } void mlp_c_function::destroy(mlp_context *ctx){ ctx->clear_error() ; if (cif != NULL){ CInvContext *cic = (CInvContext *)ctx->get_runtime_data(rt) ; cinv_status_t st = cinv_function_delete(cic, cif) ; if (st == CINV_ERROR){ ctx->set_error(MLP_FUNCTION_ERROR, "Can't delete function %s: %s\n", name.c_str(), cinv_context_geterrormsg(cic)) ; } } mlp_function::destroy(ctx) ; }