我有一个pyd pytest.pyd,其中声明了两个函数: say_hello和add_numbers。所以我想用LoadLibraryEx在C++中动态加载这个pyd。但是,当我尝试调用initpytest函数时,它失败了。
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)(); // failIn输出错误:致命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);
}发布于 2021-06-08 02:14:54
如果没有合适的最小、可重复的示例,就不可能确定。然而,这可能是因为您还没有初始化解释器:(参见this question for example)。在使用任何Python函数之前,您需要调用Py_Initialize。
我是否可以建议您使用normal Python C-API tools来运行模块(而不是自己使用LoadLibraryEx!)直到您完全理解嵌入Python是如何工作的。您可以考虑使用PyImport_AppendInittab (在初始化之前)来直接设置函数,从而避免使用Python搜索路径。
https://stackoverflow.com/questions/67873992
复制相似问题