尝试使用 LoadLibraryEx 加载 pyd 并失败

Trying to load pyd with LoadLibraryEx and got failed

我有一个 pyd pytest.pyd,其中声明了两个函数:say_hello 和 add_numbers。所以我想用 LoadLibraryEx 在 C++ 中动态加载这个 pyd。但是,当我尝试调用 initpytest func 时,它失败了。

const char* funcname = "initpytest";

HINSTANCE hDLL = LoadLibraryEx(L"D:\msp\myproj\Test\pytest.pyd", NULL, LOAD_WITH_ALTERED_SEARCH_PATH);

FARPROC p = GetProcAddress(hDLL, funcname);

(*p)(); // fail

输出错误:致命 Python 错误:PyThreadState_Get:没有当前线程 Test.exe 中 0x00007FFCD0CC286E (ucrtbase.dll) 的未处理异常:请求致命程序退出。

这里是生成pyd之前的扩展代码:

#include "Python.h"

static PyObject* say_hello(PyObject* self, PyObject* args)
{
    const char* msg;

    if(!PyArg_ParseTuple(args, "s", &msg))
    {
        return NULL;
    }
    printf("This is C world\nYour message is %s\n", msg);
    return Py_BuildValue("i", 25);
}

static PyObject* add_numbers(PyObject* self, PyObject* args)
{
    double a, b;

    if (!PyArg_ParseTuple(args, "dd", &a, &b))
    {
        return NULL;
    }
    double res = a + b;
    return Py_BuildValue("d", res);
}

static PyMethodDef pytest_methods[] = {
    {"say_hello", say_hello, METH_VARARGS, "Say Hello!"},
    {"add_numbers", add_numbers, METH_VARARGS, "Adding two numbers"},
    {NULL, NULL, 0, NULL}
};

PyMODINIT_FUNC initpytest(void)
{
    Py_InitModule("pytest", pytest_methods);
}

在没有适当的最小的、可重现的例子的情况下,这是不可能确定的。但是,这可能是因为您还没有初始化解释器:(参见 )。在使用任何 Python 函数之前,您需要先调用 Py_Initialize

我能否建议您将 normal Python C-API tools 用于 运行 模块(而不是自己使用 LoadLibraryEx!),直到您完全理解如何嵌入 Python作品。您可能会考虑 PyImport_AppendInittab(在初始化之前)直接设置您的函数并避免使用 Python 搜索路径。