【问题标题】:WindowsError exception access violation - in simple python c++ ctypes interfaceWindowsError 异常访问冲突 - 在简单的 python c++ ctypes 接口中
【发布时间】:2014-04-16 09:48:48
【问题描述】:

我有一个非常简单的测试用例,我无法开始工作,我正在尝试使用 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),包括一个外部 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 问题。但是希望它可以为这种情况提供一些启示。

【问题讨论】:

  • 你的代码没问题。它在这里工作。
  • @DavidHeffernan,感谢您的检查。也许我对它在我的 Windows 机器上的运行或编译方式有疑问
  • 我看到您使用的是 64 位窗口 - This Q&A 可能会有所帮助。
  • @etheranger,我已尝试为示例指定 restypes 和 argtypes。你认为我可能需要以某种方式修改它们吗?
  • 只是检查一下,您运行的是 64 位 python 解释器吗?我不希望 32 位的甚至加载 DLL,但谁知道:/

标签: python c++ ctypes


【解决方案1】:

在注意到其他问题后,原来是我的编译器的配置有问题,重新安装/不同的编译器允许这段代码运行。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2013-03-06
    • 2023-03-14
    • 2015-11-19
    • 2019-06-19
    • 1970-01-01
    • 2012-05-02
    • 1970-01-01
    • 2020-06-15
    相关资源
    最近更新 更多