简体   繁体   中英

C code crashes attempting Python remote procedure call via xmlrpc

I'm trying to create C code that creates an Python xmlrpc client and calls methods on the xmlrpc server (I'm thinking of using this as IPC for a hook DLL).

Here's the code ... I'm not going to layer in reference counting until it works.

#include <Python.h>
#define WIN32_LEAN_AND_MEAN
#include <Windows.h>

static PyObject *xmlrpc_server_proxy = NULL;
static PyObject *set_server_proxy(void);
static void say_hi(void);

int main()
{
    xmlrpc_server_proxy = set_server_proxy();
    say_hi();
    return 0;
}

static PyObject *
set_server_proxy()
{
        PyObject *xmlrpc_client_mod, *xmlrpc_server_proxy_class, *location, *args;
        PyObject *result;
        Py_Initialize();
        xmlrpc_client_mod = PyImport_ImportModule("xmlrpc.client");
        xmlrpc_server_proxy_class = PyObject_GetAttrString(xmlrpc_client_mod, "ServerProxy");
        location = PyUnicode_FromString("http://127.0.0.1:8000/");
        args = Py_BuildValue("(O)", location);
        result = PyObject_CallObject(xmlrpc_server_proxy_class, args);
        Py_Finalize();
        return result;
}

static void say_hi()
{
    PyObject_CallMethod(xmlrpc_server_proxy, "say_hi", "()");
}

I've confirmed that my Python xmlrpc server works fine when called from another Python server proxy. When I try to run the above executable, it crashes on the PyObject_CallMethod() . Why?

Near the end of set_server_proxy() you are calling Py_Finalize() which destroys the interpreter, and subsequently you are calling say_hi() which assumes the interpreter still exists. When the Python interprer code attempts to raise an error, the PyErr_Occurred() function gets a pointer to the current thread state, which is NULL ; it dereferences it and this generates the segfault.

Move your interpreter initialization calls inside the main() function:

int main()
{
    Py_Initialize();
    xmlrpc_server_proxy = set_server_proxy();
    say_hi();
    Py_Finalize();
    return 0;
}

Secondarily, if you are trying to use Python's standard xmlrpclib.ServerProxy you may need to change your import to:

xmlrpc_client_mod = PyImport_ImportModule("xmlrpclib");

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM