python - 为什么使用python调用c++程序时静态变量没有释放

标签 python c++

我正在使用 Python 的 C 扩展,并且在将字符串从 Python 传递到 C 程序时遇到了问题。以下面为例: python代码:

import ctypes
from ctypes import *
from numpy.ctypeslib import ndpointer
from scipy.cluster.hierarchy import dendrogram, linkage
from os import system

ls_str = [ ['a','b'] , ['c','d'] ]
for str1, str2 in ls_str:
    system('g++ -c -fPIC *.cpp -o test.o')
    system('g++ -shared -Wl,-soname,test.so -o test.so test.o')
    lib = cdll.LoadLibrary('./test.so')
    lib.Test.argtypes = [c_char_p]
    x = create_string_buffer(str1)
    y = create_string_buffer(str2)
    val = lib.Test(x,y)

.cpp 文件:

#include <iostream>
#include <string>
using namespace std;

extern "C"
int Test(char *str1, char *str2){
    static string string1 = str1, string2 = str2;
    // string string1 = str1, string2 = str2;
    cout << "str1 = " << str1 << endl;
    cout << "str2 = " << str2 << endl;
    cout << "string1 = " << string1 << endl;
    cout << "string2 = " << string2 << endl;
    return 0;
}

当我将 string1string2 定义为 static 时,我得到以下输出:

str1 = a
str2 = b
string1 = a
string2 = b
str1 = c
str2 = d
string1 = a
string2 = b

然后我删除static,输出变为:

str1 = a
str2 = b
string1 = a
string2 = b
str1 = c
str2 = d
string1 = c
string2 = d

我发现在函数中,比如Test(),当一个变量被定义为static时,即使我调用Test( ) 来自 Python 多次。但我曾经认为每次Python的调用完成后,C程序中的函数就会被释放。 为什么会出现这种情况?这是 static 设计的目标吗? 谢谢大家对我的帮助!

最佳答案

这是预期的。当声明为静态时,它们会在第一次调用函数时初始化一次。当不是静态时,它们会在每次调用函数时初始化。

除非卸载动态库,否则该函数不会“释放”。我不确定 ctypes 是否允许显式卸载库。当引用计数为零时,它们应该被卸载,因此请在 lib.Test 之后尝试 del lib

参见:How can I unload a DLL using ctypes in Python?

关于python - 为什么使用python调用c++程序时静态变量没有释放,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43304335/

相关文章:

python - 如何在 Python3 中像 printf 一样打印?

python - 使用 group-by 计算 Pandas 数据帧上的累积移动平均值

c++ - 将 C/C++ 标准库拉入您的项目命名空间,好主意吗?

c++ - 使用 visual studio 9 构建的命令行应用程序不将 *.NEF 作为输入,而使用 gcc 构建的同一个应用程序却接受 - 为什么?

c++ - 为什么 std::move 需要前向引用?

python - 配置Apache2 httpd.conf以允许上传文件;使用python客户端配合pycurl进行上传

python - 我可以在 Django 的 View 中声明变量时将变量传递到表单中吗

python - 使用 Pandas 和 spaCy 进行分词

c++ - 如何找出某个标准C++函数的实现细节?

c++ - 在右值方法中从 *this 移动?