how to deal with the PyObject* from C++ in Python

c++, ctypes, dll, pyobject, python

Solution

You have a number of issues of your code, some modifications:

#include <Python.h>
#include <vector>

extern "C" PyObject* _stdcall getList(){
  PyObject *PList = PyList_New(0);

  std::vector <int> intVector;
  std::vector<int>::const_iterator it;

  for(int i = 0 ; i < 10 ; i++){
    intVector.push_back(i);
  }

  for(it = intVector.begin(); it != intVector.end() ; it++ ){
    PyList_Append(PList, Py_BuildValue("i", *it));
  }

  return PList;
}

compile it:

> g++ -Wall -shared lib.cpp -I \Python27\include -L \Python27\libs -lpython27 -o lib.dll -Wl,--add-stdcall-alias

now you can load it as any function and set the `getList` return type to `py_object` as:

import ctypes

lib = ctypes.WinDLL('lib.dll')

getList = lib.getList
getList.argtypes = None
getList.restype = ctypes.py_object

getList()

test it:

>>> import ctypes
>>>
>>> lib = ctypes.WinDLL('lib.dll')
>>>
>>> getList = lib.getList
>>> getList.argtypes = None
>>> getList.restype = ctypes.py_object
>>> getList()
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
>>>
>>>

Problem

I create DLL wrote in C++ , the exporting function returns PyObject * .Then I use ctypes to import the DLL in Python . Now , how can I get the real PyObject ?? here's some part of c++ code: ``` PyObject* _stdcall getList(){ PyObject * PList = NULL; PyObject * PItem = NULL; PList = PyList_New(10); vector <int> intVector; int i; for(int i=0;i<10;i++){ intVector.push_back(i); } for(vector<int>::const_iterator it=intVector.begin();it<intVector.end();it++){ PItem = Py_BuildValue("i", &it); PyList_Append(PList, PItem); } return PList; } ``` and some python code : ``` dll = ctypes.windll.LoadLibrary(DllPath) PList = dll.getList() ``` *I wanna get the real python list containing 1,2,3,4...10 ? * Am I clear ?? Thanks advance

Original source