I am using Python3.6. I have created a C++ extension using (pybind11)[https://github.com/pybind/pybind11]. I copied the compiled *.pyd
file along with the dependent dll to the site packages. But when I try to load any functions from the external DLL, python complains that the function is not present. If I want to access the function, I need write
sys.path.append(r'C:\Users\test\AppData\Local\Programs\Python\Python36\Lib\site-packages\CppProject')
or I need to add the same path to the PYTHONPATH
environment variable.
Why Python is not able to load the function even though it is present in the same path as the pyd? I don't want to append the sys path everytime I need to use the module or use the environment variable? Is there any way to avoid this? Is there any way to add this path to the sys automatically whenever the user import the module?
Example:
CppExport.dll
#ifdef CPPEXPORT_EXPORTS
#define CPPEXPORT_API __declspec(dllexport)
#else
#define CPPEXPORT_API __declspec(dllimport)
#endif
extern "C" CPPEXPORT_API double sin_impl(double x);
const double e = 2.7182818284590452353602874713527;
double sin_impl(double x){
return (1 - pow(e, (-2 * x))) / (2 * pow(e, -x));
}
CppProject.pyd
PYBIND11_MODULE(CppProject, m) {
m.def("sin_impl", &sin_impl, R"pbdoc(
Compute a hyperbolic tangent of a single argument expressed in radians.
)pbdoc");
#ifdef VERSION_INFO
m.attr("__version__") = VERSION_INFO;
#else
m.attr("__version__") = "dev";
#endif
}
Setup.py
from setuptools import setup
import distutils
import sys
from setuptools.dist import Distribution
from distutils.sysconfig import get_python_lib
relative_site_packages = get_python_lib().split(sys.prefix+os.sep)[1]
date_files_relative_path = os.path.join(relative_site_packages, "CppProject")
class BinaryDistribution(Distribution):
"""Distribution which always forces a binary package with platform name"""
def has_ext_modules(foo):
return True
setup(
name='CppProject',
version='1.0',
description='CppProject Library',
packages=['CppProject'],
package_data={
'CppProject': ['CppProject.pyd'],
},
data_files = [(date_files_relative_path, ["CppExport.dll"])],
distclass=BinaryDistribution
)
In Python:
from CppProject import sin_impl
Error:
ImportError: cannot import name 'sin_impl'
Full Code is present in Github