小编Abh*_*aya的帖子

通过ctypes为返回到python的对象释放内存

我正在使用ctypes将MyDll中的c函数扩展为python.

from ctypes import cdll
libX = cdll.LoadLibrary("d:\\MyTestProject\\debug\\MyDll.dll")
Run Code Online (Sandbox Code Playgroud)

进一步在.py文件中我有一个类,其方法通过ctypes调用MyDll中的函数.

Class MyTestClass:
       def __init__(self,id):
           libA.MyTestClassInDLL_new.restype = ctypes.c_void_p
           self.obj = libA.MyTestClassInDLL_new(id)
Run Code Online (Sandbox Code Playgroud)

相应的c函数MyTestClassInDLL_new已在MyDll中定义为 -

extern "C" __declspec(dllexport) void * MyTestClassInDLL_new(char* id) 
{ 
     pTestObject = new CMyTestClassInDLL(CString(id)); 
     return (void *)pTestObject;    
}
Run Code Online (Sandbox Code Playgroud)

注意我使用new来在我的vc ++ dll中实例化该对象并返回指向它的指针.我在.py文件中将此函数的restype设置为ctypes.c_void_p.

我执行的脚本包含以下内容 -

testob = MyTestClass("5")
Run Code Online (Sandbox Code Playgroud)

这很好用.我在这里获得的testob进一步用于调用其内部从MyDll调用c函数的方法.

但是,该对象是使用MyDll中的new创建的,并通过MyTestClassInDLL_new()函数返回.这个物体是如何被摧毁的?在某个地方我需要使用delete pTestObject,以便调用它的析构函数来执行清理并释放内存.

python ctypes

5
推荐指数
1
解决办法
1852
查看次数

使用ctypes将元组的元组从c返回到python

我需要从我的c dll返回一个二维异构数据数组到python.

我为此目的从我的c dll返回一个元组元组.它以PyObject*的形式返回

这个元组元组需要作为tup [0] [0]访问第一行第一列tup [0] [1]第一行第二列......依此类推......在我的python代码中.

我使用ctypes来调用返回元组元组的c函数.但是,我无法访问python代码中返回的PyObject*.

extern "C" _declspec(dllexport) PyObject *FunctionThatReturnsTuple()
{   
    PyObject *data = GetTupleOfTuples();    

    return data;    //(PyObject*)pFPy_BuildValue("O", data);    
}
Run Code Online (Sandbox Code Playgroud)

在python脚本中我使用以下 -

libc = PyDLL("MyCDLL.dll")

x = libc.FunctionThatReturnsTuple()

if x != None :
   print str( x[0][0] )
   print str( x[0][1] )
Run Code Online (Sandbox Code Playgroud)

但是我得到一个错误 - 'int'对象不是可订阅的.我认为这是因为x被接收为指针.

实现这一目标的正确方法是什么?

ctypes

3
推荐指数
1
解决办法
1366
查看次数

通过 ctypes 使用扩展 dll 中的类所需的帮助

我在 Visual Studio 中编写了以下代码来创建扩展 DLL。

class A
{
     public:
      void someFunc()
      {

      }
};


  extern "C" __declspec(dllexport) A* A_new() 
  { 
     return new A(); 
  }

 extern "C" __declspec(dllexport) void A_someFunc(A* obj) 
  { 
    obj->someFunc(); 
  }

  extern "C" __declspec(dllexport) void A_destruct(A* obj) 
  { 
    delete obj; 
  }
Run Code Online (Sandbox Code Playgroud)

我想在python中使用ctypes来使用A类。我在wrapper.py中编写了以下代码——

从 ctypes 导入 Windll

libA = Windll.LoadLibrary("c:\ctypestest\test.dll")

A类: def init (self): self.obj = libA.A_new()

def __enter__(self):
    return self

def __exit__(self):
   libA.A_destruct(self.obj)

def some_func(self):
   libA.A_someFunc(self.obj)
Run Code Online (Sandbox Code Playgroud)

在 python 2.7.1 命令提示符下,我执行以下操作 -

import 包装器 as w ----> 工作正常

a …
Run Code Online (Sandbox Code Playgroud)

python ctypes

2
推荐指数
1
解决办法
2848
查看次数

标签 统计

ctypes ×3

python ×2