【发布时间】:2021-07-28 22:10:18
【问题描述】:
libtestm.dll 代码
#pragma once
#define EXPORT extern "C" __declspec(dllexport)
#include <iostream>
#include <vector>
class TestValue
{
public:
std::vector<int> v;
TestValue()
{
for (size_t i = 0; i < 10; i++)
{
v.push_back(i);
}
}
~TestValue()
{
std::cout << "Deteled Test Value" << std::endl;
}
};
EXPORT TestValue *TestReturn()
{
return new TestValue();
}
EXPORT size_t TestData(TestValue *pt, int **array)
{
*array = pt->v.data();
return pt->v.size();
}
EXPORT void TestDelete(TestValue *pt)
{
if(pt)
{
delete pt;
}
}
TestLib.py
import os, sys
from ctypes import *
import Libs.Utils as u
__dllname__: str = 'libtestm.dll'
__dllfile__: str = None
__dll__: cdll = None
__dllfile__, __dll__ = u.FindLoadDll(__dllname__, __file__) # get dll from this method
if __name__ == "__main__":
v = __dll__.TestReturn()
__dll__.TestDelete(v)
运行此代码时的控制台输出
Deteled Test Value
Traceback (most recent call last):
File "d:\MyProjects\GitRepo\CodePython\Dlls\TestLib.py", line 31, in <module>
__dll__.TestDelete(v)
OSError: exception: access violation reading 0x00000000A20E2490
c++标准库与python的ctypes一起使用很困难,所以我尝试通过将它包装在一个类中来使用它。成功释放指向动态分配变量的指针,但发生错误。请让我知道我错了什么。谢谢。
【问题讨论】: