WindowsError异常访问冲突 - 在简单的Python C++ ctypes接口中
我有一个非常简单的测试案例,但我无法让它正常工作。我正在尝试使用ctypes将C++和Python连接起来。
在处理双精度浮点数时出现了错误,这里是我在C++中尝试使用“cout”时遇到的问题。
错误信息是:
WindowsError: exception: access violation writing 0x.....
问题出在以下C++代码的cout那一行:
#include "testgeo.h"
#include <iostream>
TestGeo::TestGeo() : td_(0),
ti_(0) {
std::cout<<td_<<std::endl; // problem line
}
这段代码有一个头文件(testgeo.h),其中包含一个extern C部分:
class TestGeo {
public:
TestGeo();
~TestGeo(){};
private:
double td_;
int ti_;
};
extern "C" {
__declspec(dllexport) TestGeo* TestGeo_new() {
return new TestGeo();
}
}
运行这段代码的Python文件是(testgeo.py):
import ctypes
lib = ctypes.cdll.LoadLibrary('testgeo.dll')
class TestGeo(object):
lib.TestGeo_new.argtypes = []
lib.TestGeo_new.restype = ctypes.c_void_p
def __init__(self):
self.obj = lib.TestGeo_new()
if __name__ == "__main__":
testGeoObj = TestGeo()
编辑1:我仍然在挣扎,而且我对编程还很陌生。有没有办法让我进一步调查这个内存错误,以便找到一些线索?
编辑2:我想分享一下我是怎么编译的,以防这有什么问题:
x86_64-w64-mingw32-g++ -c testgeo.cpp -o testgeo.o -std=c++11 -O2 -Wall -Wextra -Weffc++ -pedantic
x86_64-w64-mingw32-g++ -shared -o testgeo.dll testgeo.o
运行代码:
python testgeo.py
编辑3:这段代码在我的Linux机器上可以正常工作……这让我对Windows上的问题仍然感到困惑。不过希望这能对情况有所帮助。
1 个回答
0
我发现了其他问题,结果发现是我的编译器设置出了问题。重新安装或者换一个编译器后,这段代码就能正常运行了。