-3

通过嵌入 python 的 C++ 代码编写的代码调用外部 python 类并执行该类的方法(FileHandler)。这样可行。我在 C++ (libSome.so) 中生成了该代码的库,以便在带有 c_types 的 python 中使用,并制作一个包装器来尝试运行上述方法会产生分段错误。有任何想法吗?

(C++)这是嵌入代码,然后生成为共享库 (libSome.so):

...
    /* Funcion de python */
        setenv("PYTHONPATH", ".", 1);

        Py_Initialize();

        PyObject* module = PyImport_ImportModule("filehandler");
        assert(module != NULL);

        PyObject* class = PyObject_GetAttrString(module, "FileHandler");
        assert(class != NULL);

        PyObject* inst = PyInstance_New(class, NULL, NULL);
        assert(inst != NULL);
        result = PyObject_CallMethod(inst, (char*)"write", (char*)"(iiii)",ori,serv, id, timeStamp);
        assert(result != NULL);
        Py_Finalize();

(Python) 库使用的代码

import os

class FileHandler:
     def __init__(self):
          self.workingDirectory = os.getcwd()
          pass

     def write(self, NodoOrigen, Servicio, Id, payload):
          try:
           os.mkdir(str(NodoOrigen))
          except:
           pass

      os.chdir(str(NodoOrigen)+"/")
      try:
           os.mkdir(str(Servicio))
      except:
           pass

      os.chdir(self.workingDirectory)
      os.chdir(str(NodoOrigen)+"/"+str(Servicio)+"/")
      try:
           f = open(str(Id),"a")        
      except:
           print "No se puede abrir el archivo"
      f.write(str(payload))
      f.close()
      os.chdir(self.workingDirectory)
4

2 回答 2

0

我不确定这是否是您的问题,因为这里没有足够的信息,但 ctypes 仅用于调用 C 函数;要调用 C++ 函数,您需要使用extern "C"块中的函数包装 C++ 函数。

有关此示例,请参阅此答案:https ://stackoverflow.com/a/145649/121714

于 2013-10-08T02:38:15.750 回答
0

我认为问题可能与您的使用有关PyInstance_Newhttps ://mail.python.org/pipermail/python-list/2003-March/195516.html

也许试试这个:

PyObject* inst = PyObject_CallObject(class, NULL);

并使 FileHandler 从 Python 代码中的对象继承。

类文件处理程序(对象):
    ...

这是你的实际代码吗?如果是 C++,则不应让您使用名为 的变量class,而assert(instance != NULL);应阅读assert(inst != NULL);

另外,哪条线实际上导致了段错误?

另一种可能性:如果你从 Python 开始,然后调用调用 Python 的 C++,C++ 代码不应该调用Py_Initialize();Py_Finalize();(但是,如果你有一个嵌入 Python 的 C++ 应用程序,那很好)

于 2013-10-08T23:18:37.590 回答