我正在使用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
时,即使我从Python多次调用Test()
,它的值也不会改变。但我曾经认为每次Python调用完成后,C程序中的函数都会被释放。
为什么会这样?它是static
的目标吗?
谢谢大家的帮助!
答案 0 :(得分:2)
这是预期的。声明static
时,在第一次调用函数时,它们初始化。如果不是static
,则会在每次调用函数时初始化它们。
该功能未发布&#34;除非卸载动态库。我不确定ctypes
是否允许显式卸载库。当refcount归零时应该卸载它们,所以在del lib
之后尝试lib.Test
。