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