wasi-sdk
wasi-sdk copied to clipboard
How to call Python Function
I need to call python Function in c++ code, and link with wasi-sdk libs.
But fault at:
the cpp file is:
//python-call.cpp
#include "/usr/include/python3.6/Python.h"
#include <malloc.h>
#include <stddef.h>
#include <stdint.h>
#include "Dispatch.h"
#include "KeyValue.h"
#include "Environment.h"
#include "Message.h"
#include "Response.h"
#include "StringArray.h"
#include "Value.h"
#include "WasmExtensions.h"
bool initialize_contract(const Environment& env, Response& rsp)
{
return rsp.success(true);
}
bool compute_sum(const Message& msg, const Environment& env, Response& rsp)
{
Py_Initialize();
PyObject* pModule = NULL;
PyObject* pFunc = NULL;
PyObject* pName = NULL;
PyRun_SimpleString("import sys");
PyRun_SimpleString("sys.path.append('/root/private-data-objects/contracts/wawaka/python-call')");
pModule = PyImport_ImportModule("Handle");//Handle.py contains def HandleFc(creator_id_,block_id,url)
pFunc = PyObject_GetAttrString(pModule, "HandleFc");//HandleFc can fetch the data from sservice and compute a result.
PyObject* pArgs = PyTuple_New(3);
PyTuple_SetItem(pArgs, 0, Py_BuildValue("s", env.creator_id_));
PyTuple_SetItem(pArgs, 1, Py_BuildValue("s", msg.get_string("BlockID")));
PyTuple_SetItem(pArgs, 2, Py_BuildValue("s", msg.get_string("DataURL")));
PyObject* pReturn = PyEval_CallObject(pFunc, pArgs);
int nResult;
PyArg_Parse(pReturn, "i", &nResult);
Py_Finalize();
ww::value::Number v((double)nResult);
return rsp.value(v, false);
}
contract_method_reference_t contract_method_dispatch_table[] = {
CONTRACT_METHOD(compute_sum),
{ NULL, NULL }
};
Thanks for any tips.
Hi, you may want to take a look around existing work like https://github.com/panda3d/panda3d/tree/webgl-port which can give you a static emscripten wasm lib with both Python 3.8+ and C++ to link to and use ( proof here https://pmp-p.github.io/panda3d-next/py3/ ) , also do not forget to initialize properly libpython as shown in cpython embedding examples.
I think the original question was answered by @pmp-p (thanks!). Though this Python topic is not directly tied to wasi-sdk, for anyone who might be interested in the state of Python + WebAssembly, here is a post that links to various other places that you may find helpful: Python in WebAssembly.