0

I have the following c++ and header file, which I would like to compile in Cython: c++ code:

\\ CA.cpp c++ code

#include "CA.h"
#include<iostream>
#include <vector>
Cell::Cell() {}
// construct cell: cell is defined with position (x,y,z coordinates) and neighborhood
Cell::Cell(int x, int y, int z) {
    this->x = x;
    this->y = y;
    this->z = z;
    std::vector<int> ngh;
}

// Return the neighbors of the cell
void Cell::neighbors( ) {
    std::vector<int> a{ -1, 0, 1 };
    std::vector<int> ranges(gridSize, 0);
    for (int i = 0; i < ranges.size(); i++) {
        ranges[i] = i;
    }


    for (int i = -1; i <= 1; i++) {
        for (int j = -1; j <= 1; j++) {
            for (int k = -1; k <= 1; k++) {
                int x_ngh = ranges[Cell::x + i];
                int y_ngh = ranges[Cell::y + j];
                int z_ngh = ranges[Cell::z + k];

            int id_ngh = x_ngh + (y_ngh - 1) * gridSize + (z_ngh - 1) * gridSize * gridSize;
            Cell:ngh.push_back(id_ngh);
            }
        }
    }
}


and header file:

\\CA.h
    #ifndef CA_H
    #define CA_H
    #include <vector>

    const int gridSize = 400;
    class Cell {
    public:
        int x, y, z;
        std::vector<int> ngh;
        Cell();
        Cell(int x, int y, int z);
        void neighbors();
    };
    #endif

In order to compile the code using cython I created CA.pxd file:

cdef extern from "CA.cpp":
    pass

# Declare the class with cdef
cdef extern from "CA.h":
    cdef cppclass Cell:
        Cell() except +
        Cell(int, int, int) except +
        int x,y,z
        neighbors()

and CA.pyx

# distutils: language = c++
from CA cimport *
from libcpp.vector cimport vector
cdef class PyCell:
    cdef  Cell c_cell

    def __cinit__(self, int x, int y, int z):
        self.c_cell = Cell(x,y,z)

    def neighbors(self):
        return self.c_cell.neighbors()

Finally, I created setup.py file:

from Cython.Build import cythonize
setup(ext_modules=cythonize("CA.pyx"))

When I run the command: python setup.py build_ext --inplace

I get an error LINK : error LNK2001: unresolved external symbol PyInit_CA. I don't know why. Any help greatly appreciated.

Emilia
  • 21
  • 3
  • The problem is probably along the lines of https://stackoverflow.com/q/50719086/5769463, with the difference that you use Windows and some strange file locking mechanism play into it, that the original CA.cpp isn't overwritten (or something with case insensivity of the Window's file system). Name your extension differently. – ead May 20 '20 at 11:34
  • thank you so much. I renamed the pyx and pyd file to sth else and now, the code work! Thanks a lot! – Emilia May 20 '20 at 11:51

0 Answers0