Skip to main content
 首页 » 编程设计

python之当 dll 具有嵌入式 Python 解释器时,将函数从 dll(用 C++ 编程)导入 Python 脚本

2024年12月31日8rubylouvre

我用 C++ 编写了一个使用嵌入式 Python 解释器的库 (dll)。 当库被 c++ 程序使用时,在嵌入式解释器中执行 Python 脚本工作正常。

如果我从 Python 程序调用 dll 的函数,我就会遇到麻烦。 当 dll 通常通过调用 Py_Initialize() 启动嵌入式解释器时,已经有一个解释器在运行(我可以通过调用 Py_IsInitialized() 来测试它)。 当我尝试使用这个解释器时,程序崩溃了。

重现该行为的最小示例:

dll 代码:

#include "stdafx.h" 
#include <Python.h> 
 
extern "C" __declspec(dllexport) 
int testIsInitialized() 
{ 
  return Py_IsInitialized(); 
} 
 
extern "C" __declspec(dllexport) 
void testRunSimpleString() 
{ 
  PyRun_SimpleString("print('test')"); 
} 

Python 脚本:

import ctypes 
 
dll=ctypes.windll.LoadLibrary('pytest.dll') 
 
# test if Python interpreter is initialized 
print(dll.testIsInitialized()) 
 
# test if we can run a simple Python script 
dll.testRunSimpleString() 

输出:

1 
Traceback (most recent call last): 
  File "test_dll.py", line 9, in <module> 
    dll.testRunSimpleString() 
OSError: exception: access violation reading 0x0000000000000010  

我的主要问题是: 如何从由不同 Python 程序导入的 C++ 库中执行 Python 代码?

更新

当我在我的 testRunSImpleString() 函数中获取全局解释器锁 (GIL) 时,该示例有效。 我不明白为什么这是必要的。

请您参考如下方法:

ctypes库有几个类来加载不同类型的 DLL。两个相关的类是:

  • ctypes.CDLL (即 C DLL)——用于加载使用标准 C 调用约定的 DLL。这包括定义 extern "C" 的 C++ DLL。
  • ctypes.PyDLL - 类似于 C DLL,只是在函数调用期间不释放 Python GIL。用于直接调用 Python C API 函数。

加载使用 Python C API 的 C++ DLL(即 Python.h)时,使用 ctypes.PyDLL:

import ctypes 
 
dll = ctypes.PyDLL('pytest.dll') 
 
# then do whatever 
dll.testRunSimpleString.argtypes = [] 
dll.testRunSimpleString.restype = None 
dll.testRunSimpleString() 

使用 PyDLL 时要记住的一件事是您不需要调用 Py_Initialize() 或 Py_Finalize()/Py_FinalizeEx() 来自 C++ API,因为解释器已经在运行。您可以先检查(并存储)Py_IsInitialized() 以查看是否需要启动/停止新的解释器。