0

I'm trying to create a cython wrapper from C++ code (it just adds two numbers). I have the following code:

myc.cpp:

#include "myc.hpp"

template <class T>
T add(T a,T b){
    return a+b;
}

myc.hpp:

template <class T>
T add(T a,T b);

myc.pxd:

cdef extern from "myc.hpp":
    T add[T](T a,T b)

mymodule.pyx:

# distutils: libraries = myc
# distutils: library_dirs = "."
# distutils: language = c++
# distutils: sources = myc.cpp

from myc cimport add

cpdef double add2(double a,double b):
    return add(a,b)

main.py:

from mymodule import add2

a = 32.0

print(add2(a,a))

The files are all in the same folder. Now, if instead of using templates in the 'add' function definition, I use double type, the code works fine. If I change the 'from "myc.hpp":' from the myc.pxd file to 'from "myc.cpp":', the code works fine too. So, why doesn't it work when I define the function from the header file in the myc.pxd?

PS: I call cythonize -i mymodule.pyx, and the following error appears at the end of the output:

mymodule.obj : error LNK2001: unresolved external symbol "double __cdecl add(double,double)" (??$add@N@@YANNN@Z) C:\Users\######\Desktop\#######\mymodule.cp37-win_amd64.pyd : fatal error LNK1120: 1 unresolved externals error: command 'C:\Program Files (x86)\Microsoft Visual Studio\2019\BuildTools\VC\Tools\MSVC\14.28.29333\bin\HostX86\x64\link.exe' failed with exit status 1120

Dharman
  • 30,962
  • 25
  • 85
  • 135
Rodolfo
  • 96
  • 7
  • This is really just a fairly basic C++ problem. The definition of a C++ template has to be visible to the compiler at the point you need it, hence it has to be defined in the header. (As an alternative you could explicitly request `add` to be defined in the C++ file, but that's a little more tedious and usually not what you want) – DavidW Dec 26 '20 at 17:04
  • It is already defined in the header file. – Rodolfo Dec 26 '20 at 17:19
  • I understand it now :) thanks – Rodolfo Dec 26 '20 at 17:23

0 Answers0