我正在使用基于C ++的库,其返回类型是char指针。我在Python中调用这个C ++函数。
我的问题是我可以从Python中删除C ++函数中分配的内存吗?
Python代码
lib.TagGetName.restype = c_char_p
lib.TagGetName.argtypes=[c_int]
data = 1
cmt = (b"this is comment for Voltage")
result = lib.TagGetName(data)
Python输出
Kernel process terminated for restart. (0)
Python 3.4.3 (v3.4.3:9b73f1c3e601, Feb 24 2015, 22:43:06) on Windows (32 bits).
This is the IEP interpreter.
Type 'help' for help, type '?' for a list of *magic* commands.
运行脚本:" D:\ QTDev \ test.py"
1
SELECT sTagName FROM TagDataInfo where iTagId = 1;
Return value--> b'Voltage\xfd\xfd\xfd\xfd\xdd`\x18x'
print ("Return value-->" , result)
C ++函数代码
USE_MATH char* TagGetName(int iTagId)
{
char* cName;
//string cName = "";
sqlite3_stmt *stmtCreate = NULL;
sqlite3 *m_pdbObj;
cout<<iTagId<<endl;
if (sqlite3_open_v2("D:\\QTDev\\forPythonDLL\\Neha_Test_Use\\TagData", &m_pdbObj, SQLITE_OPEN_READWRITE, NULL) != SQLITE_OK)
{
return cName;
}
char cQuery[1024] = {0};
sprintf(cQuery,"SELECT sTagName FROM TagDataInfo where iTagId = %d;",iTagId);
cout<<cQuery<<endl;
if (sqlite3_prepare_v2(m_pdbObj, cQuery, -1, &stmtCreate, 0) == SQLITE_OK)
{
sqlite3_step(stmtCreate);
if(sqlite3_column_text(stmtCreate, 0))
{
cName = new char[strlen((char*)sqlite3_column_text(stmtCreate, 0))+1];
memset(cName,0x00,(strlen((char*)sqlite3_column_text(stmtCreate, 0))+1));
memcpy(cName,(char*)sqlite3_column_text(stmtCreate, 0),strlen((char*)sqlite3_column_text(stmtCreate, 0)));
cout<<"Cname="<<cName<<endl;
cout<<"Database Name="<<(char*)sqlite3_column_text(stmtCreate, 0)<<endl;
}
sqlite3_finalize(stmtCreate);
}
else
{
return cName;
}
sqlite3_exec(m_pdbObj, "COMMIT", 0, 0, 0);
return cName;
}
答案 0 :(得分:3)
在Python中,您无法删除在C ++中分配的内存。 你必须从C ++导出另一个函数,它只包装free()/ delete调用,并从python中调用它。
顺便说一句,请记住python使用的是UTF-16,而C ++可能正在使用UTF-8,并且需要进行一些字符串转换(ctype可以正确执行此操作)