从c ++“library”调用python方法

时间:2013-10-07 19:54:14

标签: c++ python extending

通过用C ++代码编写的代码嵌入python调用外部python类并执行类的方法( FileHandler )。这样可行。 我在C ++(libSome.so)中生成一个代码库,用于在python中使用c_types并使包装器尝试运行上面的方法给出了分段错误。有什么想法吗?

(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)

2 个答案:

答案 0 :(得分:0)

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

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

答案 1 :(得分:0)

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

也许试试这个:

PyObject* inst = PyObject_CallObject(class, NULL);

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

class FileHandler(object):
    ...

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

另外,哪一行实际上导致了段错?

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

相关问题