简体   繁体   中英

Return string from python to C++

My python code has methods with returning String.

import urllib.request
import ssl
import suds.transport.http
from suds.client import Client

class UnverifiedHttpsTransport(suds.transport.http.HttpTransport):
  def __init__(self, *args, **kwargs):
     super(UnverifiedHttpsTransport, self).__init__(*args, **kwargs)
  def u2handlers(self):
     handlers = super(UnverifiedHttpsTransport, self).u2handlers()
     context = ssl.create_default_context()
     context.check_hostname = False
     context.verify_mode = ssl.CERT_NONE
     handlers.append(urllib.request.HTTPSHandler(context=context))
     return handlers

url="https://atictest.com/datamanagement.asmx?WSDL"
client = Client(url, transport=UnverifiedHttpsTransport())

def ReadDataTest():
  result = client.service.ReadTestData()
  return result

def ReadGridData():
  result = client.service.ReadGridData()  
  return result

def main():
  result=ReadGridData()
  print(result)

if __name__ == "__main__":
  main() 

If ReadDataTest() method is called result has string {"Message":"You Have Successfully Connected"} .

Since this python method is called from C++, I need to parse the String return in C++.

I tried as

pFunc_readtest = PyObject_GetAttrString(pModule, "ReadDataTest");
if (pFunc_readtest && PyCallable_Check(pFunc_readtest)) {
  pValue = PyObject_CallObject(pFunc_readtest, NULL);
  if(pValue != NULL) {
     std::string m_gettextFunction = PyObject_GetAttrString(pValue, "gettext");
     printf("Result of call: %c\n", m_gettextFunction);
     Py_DECREF(pValue);
  }
}

But I have error in compilation. How to receive String from python to C++?

The PyObject_GetAttrString returns a PyObject * , handle it properly, here is the code:

pFunc_readtest = PyObject_GetAttrString(pModule, "ReadDataTest");
if (pFunc_readtest && PyCallable_Check(pFunc_readtest)) {
    pValue = PyObject_CallObject(pFunc_readtest, NULL);
    if(pValue != NULL) {
        PyObject * res = PyObject_GetAttrString(pValue, "gettext");
        if (!PyUnicode_Check(res)) {
            // not a string, return error here
        }
        std::string m_gettextFunction = std::string(PyUnicode_AsUTF8(res));
        printf("Result of call: %c\n", m_gettextFunction);
        Py_DECREF(pValue);
    }
}

If gettext is a method then call it, don't just get it:

PyObject * res = PyObject_CallMethod(pValue, "gettext", NULL);

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