Aha*_*024 1 c++ python dll ctypes pyobject
我创建了用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;
}
Run Code Online (Sandbox Code Playgroud)
和一些python代码:
dll = ctypes.windll.LoadLibrary(DllPath)
PList = dll.getList()
Run Code Online (Sandbox Code Playgroud)
*我想获得包含1,2,3,4 ... 10的真正的python列表?* 我是否清楚?谢谢你
小智 5
您的代码有很多问题,有些修改:
#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;
}
Run Code Online (Sandbox Code Playgroud)
编译它:
> g++ -Wall -shared lib.cpp -I \Python27\include -L \Python27\libs -lpython27 -o lib.dll -Wl,--add-stdcall-alias
Run Code Online (Sandbox Code Playgroud)
现在您可以将其作为任何函数加载并将getList返回类型设置py_object为:
import ctypes
lib = ctypes.WinDLL('lib.dll')
getList = lib.getList
getList.argtypes = None
getList.restype = ctypes.py_object
getList()
Run Code Online (Sandbox Code Playgroud)
测试一下:
>>> 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]
>>>
>>>
Run Code Online (Sandbox Code Playgroud)
我不太清楚你在问什么。但我想您的意思是问现在可以用 DLL 做什么。
为了正确使用它,您必须构建一个特殊的 DLL,它可以直接作为 Python 模块导入。为了确定要做什么才能使用它,最好看看其他模块,以及它们是如何做的。例如 MySQLdb可能是一名候选人。
简而言之,您让这个“包装”DLL 调用您的函数。
但如果我现在再看一下你的问题,我发现你正在尝试通过ctypes. 这也是可行的,甚至可能更好,并且您必须使用ctypes.py_object数据类型。