0

0 My aim is to embedding some python code with scipy library into C++ code, and I want to run the C++ code without any python installation. This is my current process:

1 Saving the following code as a .pyx file:

import scipy.stats as sp
cdef public float ppf(const float c, const float a, const float s):
    return sp.gamma.ppf(c, a=a, loc=0, scale=s)

2 Using "cython" to generate .c and .h file

cython XXX.pyx

3 Generating .dll file from .c and .h with Visual Studio:

extern "C"
{
    __declspec(dllexport) float __stdcall _ppf(const float c, const float r, const float k)
    {
        return ppf(c, r, k);
    }
}

BOOL WINAPI DllMain(HINSTANCE hinstDLL, DWORD fdwReason, LPVOID lpReserved)
{
    switch (fdwReason)
    {
    case DLL_PROCESS_ATTACH:
        Py_Initialize();
        PyInit_ppf();
        break;
    case DLL_PROCESS_DETACH:
        Py_Finalize();
        break;
    }
    return TRUE;
}

4 Calling the .dll file without python installation:

int main()
{
    typedef int(*pAdd)(const float c, const float r, const float k);
    HINSTANCE hDLL = LoadLibrary(_T("Win32Project.dll"));
    if (hDLL)
    {
        pAdd pFun = (pAdd)GetProcAddress(hDLL, "_ppf");
        if (pFun)
        {
            float i = pFun(0.0000001, 5.0, 1.0);
            cout << "i = " << i << endl;
        }
    }
    system("pause");
    return 0;
}

5 The code outputs a very large random value(however the correct result is fixed around 1.0). I also test a simple addition operation in step 1 without scipy dependency to verify correctness of the pipeline, and it works. But I don't know what is wrong when I use scipy library. How can I convert the python with scipy into dll correctly?

Note: I guess there should be many dependencies with scipy, so I use "pyinstaller" to generate all relative .dll files. I put these files into the Visual Studio project directory at the same level as *.exe, it still doesn't work. I don't know whether I use these files correctly, or any other reason?

gh l
  • 11
  • 3
  • Does this answer your question? [Calling Cython function from C code raises segmentation fault](https://stackoverflow.com/questions/55647555/calling-cython-function-from-c-code-raises-segmentation-fault) – ead Nov 08 '20 at 17:24
  • In your case there is no segfault, but that is UB thus for different compilers the behavior can be different. You also should always check whether a command was successfully (PyInit_xxx). – ead Nov 08 '20 at 17:27
  • Thank you for your answer. The link doesn't contain any python dependency. It also can work in my pipeline, but when I add the scipy dependency in my pyx, it doesn't work,it bothers me so much... – gh l Nov 09 '20 at 02:43
  • Right - but if you _check the return value_ when you call `PyInit_` then you'd know if it failed. You could then call `PyErr_Print()` to see why. While you're skipping these basic debugging steps it's going to be pure guesswork as to what's going wrong – DavidW Nov 09 '20 at 12:05

0 Answers0