wasi-sdk icon indicating copy to clipboard operation
wasi-sdk copied to clipboard

How to call Python Function

Open zlonqi opened this issue 3 years ago • 1 comments

I need to call python Function in c++ code, and link with wasi-sdk libs. But fault at: 微信截图_20220105220659 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.

zlonqi avatar Jan 05 '22 14:01 zlonqi

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.

pmp-p avatar Jan 06 '22 16:01 pmp-p

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.

abrown avatar Mar 13 '23 16:03 abrown