我正在使用 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;
}
当我将 string1
和 string2
定义为 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
。
关于python - 为什么使用python调用c++程序时静态变量没有释放,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43304335/