5
votes

I have a very simple test case that I can't get to work, I am trying to interface c++ with python using ctypes. I get errors when working with doubles, in this case trying to use "cout" in the c++.

The error is:

WindowsError: exception: access violation writing 0x.....

The problem lies in the cout line of the following c++ code:

#include "testgeo.h"
#include <iostream>
TestGeo::TestGeo() : td_(0),
                     ti_(0) {
    std::cout<<td_<<std::endl; // problem line
}

Which has the following header (testgeo.h), including an extern C section:

class TestGeo {

    public:
    TestGeo();
    ~TestGeo(){};

    private:
    double td_;
    int ti_;

};
extern "C" {
    __declspec(dllexport) TestGeo* TestGeo_new() {
        return new TestGeo();
    }
}   

And the python code that runs this is (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()

Edit 1: Still struggling, and I am quite new to programming. Is there anyway I can investigate the memory error further which may give me some clues?

Edit 2: I thought I would share how I am compiling in case that is something that is wrong:

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

Running the code:

python testgeo.py

Edit 3: The code works on my linux machine... which means I am still unsure about my windows problem. However hopefully it could provide some light on the situation.

1
Your code is fine. It works here. - David Heffernan
@DavidHeffernan, thanks for checking. Perhaps I am having an issue with how it runs or compiles on my windows machine specifically - windenergy
I see you're using 64 bit windows - This Q&A may help. - etheranger
@etheranger, I have attempted to specify restypes and argtypes for the example. Do you think I perhaps need to modify them somehow? - windenergy
Just checking, are you running a 64-bit python interpreter? I wouldn't expect a 32-bit one to even load the DLL, but who knows :/ - etheranger

1 Answers

0
votes

After noticing other problems it turned out that the configuration of my compiler was the issue, and a reinstall / different compiler allowed this code to run.