簡體   English   中英

如何在Python中使用C ++處理PyObject *

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

我創建用C ++寫的DLL,導出函數返回PyObject *。然后我使用ctypes在Python中導入DLL。 現在,我如何獲得真正的PyObject?

這是C ++代碼的一部分:

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;
}

和一些python代碼:

dll = ctypes.windll.LoadLibrary(DllPath)
PList = dll.getList()

* 我想獲取包含1,2,3,4 ... 10的真實python列表? *我清楚了嗎? 謝謝前進

您的代碼有很多問題,需要進行一些修改:

#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;
}

編譯:

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

現在您可以將其加載為任何函數,並將getList返回類型設置為py_object

import ctypes

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

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

getList()

測試一下:

>>> 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]
>>>
>>>

使用Visual Studio和Python 64位:
1-創建一個空的Win32項目(DLL類型)
2-右鍵單擊您的解決方案項目->配置管理器
3-主動解決方案配置(發布)
4- Active Solution Platform-> New,然后在底部的下拉列表中,選擇x64-> OK
5-在“源文件”文件夾中,添加一個空的C ++文件
6-放入您的C ++代碼(對getList的一種修改可以識別)

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

extern "C" __declspec(dllexport) PyObject* _stdcall getList();

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;
}

我不清楚您要問什么。 但是我想你是想問一下現在可以使用DLL做什么。

  1. 好吧,為了正確使用它,您必須構建一個特殊的DLL,可以將其直接導入為Python中的模塊。 為了確定如何使用此功能,最好查看其他模塊以及它們如何執行。 例如 MySQLdb可能是候選者。

    簡而言之,您有這個“包裝” DLL來調用您的函數。

  2. 但是,如果現在再看看您的問題,就會發現您正在嘗試通過ctypes加載DLL。 這也是可行的,甚至可能更好,並且您必須使用ctypes.py_object數據類型

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM