【问题标题】:Trying to load pyd with LoadLibraryEx and got failed尝试使用 LoadLibraryEx 加载 pyd 并失败
【发布时间】:2021-08-24 16:16:07
【问题描述】:

我有一个 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);
}

【问题讨论】:

    标签: winapi python-c-api dynamic-loading pyd


    【解决方案1】:

    如果没有适当的最小、可重现的示例,则无法确定。但是,这可能是因为您还没有初始化解释器:(参见this question for example)。在使用任何 Python 函数之前,您需要调用 Py_Initialize

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2023-03-26
      • 2014-06-23
      • 2013-03-10
      • 1970-01-01
      • 1970-01-01
      • 2013-05-04
      • 2020-11-19
      • 2021-12-12
      相关资源
      最近更新 更多